Access to XMLHttpRequest at 'https://xyz.herokuapp.com/products' from origin 'https://abc.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I am building my first MERN web app and I have to submit on Monday (that is in 2 days)
netlify site name : https://venerable-daffodil-ed3e93.netlify.app/

I am able to deploy my app but after deployment I cannot login, and the above is the error that I`m getting

TECH STACK = NODE + EXPRESS + REACT + MONGODB

my backend server.js looks like this

const express = require('express');
const cors = require('cors');
const app = express();
const http = require('http');
require(`dotenv` ).config();
const stripe = require('stripe')(process.env.STRIPE_SECRET);
require('./connection')
const server = http.createServer(app);
const {Server} = require('socket.io');
const io = new Server(server, {
  cors: '*',
  methods: ['GET', 'POST', 'PATCH', "DELETE"]
})

const User = require('./models/User');
const userRoutes = require('./routes/userRoutes');
const productRoutes = require('./routes/productRoutes');
const orderRoutes = require('./routes/orderRoutes');
const imageRoutes = require('./routes/imageRoutes');

app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use('/users', userRoutes);
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
app.use('/images', imageRoutes);

app.get('/', (req, res) => {
  res.send('APP IS RUNNING');
});

const PORT = process.env.PORT || 8080;

if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
  app.use(express.static('frontend/build'));
  app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname + '/frontend/build/index.html'));
  });
 }

app.post('/create-payment', async(req, res)=> {
  const {amount} = req.body;
  console.log(amount);
  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount,
      currency: 'inr',
      payment_method_types: ['card']
    });
    res.status(200).json(paymentIntent)
  } catch (e) {
    console.log(e.message);
    res.status(400).json(e.message);
   }
})


server.listen(process.env.PORT || 8080, ()=> {
  console.log(`server running at port number ${PORT}`);
})



app.set('socketio', io);

.procfile in backend

web:npm run start

backend package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
  "dev": "nodemon server.js",
  "start": "node server.js",
  "heroku-postbuild": "cd frontend && npm install && npm run build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.0.1",
    "cloudinary": "^1.30.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "mongoose": "^6.4.3",
    "nodemon": "^2.0.19",
    "socket.io": "^4.5.1",
    "stripe": "^9.11.0",
    "validator": "^13.7.0"
  }
}

On the frontend side App.js

import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Navigation from "./components/Navigation";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Signup from "./pages/Signup";
import { useDispatch, useSelector } from "react-redux";
import NewProduct from "./pages/NewProduct";
import ProductPage from "./pages/ProductPage";
import CategoryPage from "./pages/CategoryPage";
import ScrollToTop from "./components/ScrollToTop";
import CartPage from "./pages/CartPage";
import OrdersPage from "./pages/OrdersPage";
import AdminDashboard from "./pages/AdminDashboard";
import EditProductPage from "./pages/EditProductPage";
import { useEffect } from "react";
import { io } from "socket.io-client";
import { addNotification } from "./features/userSlice";

function App() {
    const user = useSelector((state) => state.user);
    const dispatch = useDispatch();
    useEffect(() => {
        const socket = io("ws://xyz.herokuapp.com/");
        socket.off("notification").on("notification", (msgObj, user_id) => {
            // logic for notification
            if (user_id === user._id) {
                dispatch(addNotification(msgObj));
            }
        });

        socket.off("new-order").on("new-order", (msgObj) => {
            if (user.isAdmin) {
                dispatch(addNotification(msgObj));
            }
        });
    }, []);
    return (
        <div className="App">
            <BrowserRouter>
                <ScrollToTop />
                <Navigation />
                <Routes>
                    <Route index element={<Home />} />
                    {!user && (
                        <>
                            <Route path="/login" element={<Login />} />
                            <Route path="/signup" element={<Signup />} />
                        </>
                    )}

                    {user && (
                        <>
                            <Route path="/cart" element={<CartPage />} />
                            <Route path="/orders" element={<OrdersPage />} />
                        </>
                    )}
                    {user && user.isAdmin && (
                        <>
                            <Route path="/admin" element={<AdminDashboard />} />
                            <Route path="/product/:id/edit" element={<EditProductPage />} />
                        </>
                    )}
                    <Route path="/product/:id" element={<ProductPage />} />
                    <Route path="/category/:category" element={<CategoryPage />} />

                    <Route path="/new-product" element={<NewProduct />} />

                    <Route path="*" element={<Home />} />
                </Routes>
            </BrowserRouter>
        </div>
    );
}

export default App;

frontend package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.8.3",
    "@stripe/react-stripe-js": "^1.9.0",
    "@stripe/stripe-js": "^1.32.0",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "autoprefixer": "10.4.5",
    "axios": "^0.27.2",
    "bootstrap": "^5.1.3",
    "react": "^18.2.0",
    "react-alice-carousel": "^2.6.1",
    "react-bootstrap": "^2.4.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.2",
    "react-router-bootstrap": "^0.26.1",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^2.4.1",
    "socket.io-client": "^4.5.1",
    "stripe": "^9.12.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Hey there, @debarati10 :wave:

Thanks for reaching out. Can you share a few more details here? What are you attempting to login to after you deploy? The Happy Paws site, your netlify account, or something else?

If it is the Happy Paws site, you will need to create a test login for us so that we can test it further.

hey! so i am attempting to login to a previously created account on the happy paws site. Not only that does not work but also creating a new account on the site, logging in to the admin account all of it does not work

The error is in the console:

You need to use Netlify Redirects for this. You can add _redirects file with the content:

/api/* https://debaratishop.herokuapp.com/:splat 200!

Since you’re using React, I believe this should go in the public folder.

Finally, you need to change your API calls from https://debaratishop.herokuapp.com/users/signup to /api/users/signup in your frontend.

1 Like

Great! this works for me. Thanks.