Fix CORS Error in React and Express - MERN Development

Fix CORS Error in React and Express - MERN Development

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

You’ve run afoul of the Same Origin Policy – it says that every AJAX request must match the exact host, protocol, and port of your site. Things that might cause this:

  • Hitting a server from a locally-served file (a request from file://demo/index.html to https://api.example.com).

  • Hitting an external API (a request from https://demosite.com to
    https://api.example.com).

  • Hitting an internal API (a request from http://example.com to http://api.example.com ).

  • Hitting a different port on the same host (webapp is on http://localhost:3000,
    API is http://localhost:3300 ).

  • Requesting over http from https or vice-versa (requesting https://example.com from http://example.com).

To be clear, this is not a React error. It afflicts all web apps equally, and most of the fixes we’ll look at below are actually modifying the server or the browser.

How to fix it

Best: CORS header (requires server changes)

CORS (Cross-Origin Resource Sharing) is a way for the server to say “I will accept your request, even though you came from a different origin.” This requires cooperation from the server – so if you can’t modify the server (e.g. if you’re using an external API), this approach won’t work.

Modify the server to add the header Access-Control-Allow-Origin: * to enable cross-origin requests from anywhere (or specify a domain instead of *). This should solve your problem. eg: Access-Control-Allow-Origin: example.com

How to Enable CORS on Express

You just need to install it in your Express project with

   npm install cors

Then require it in app.js.

var express = require('express');
// Import the library:
var cors = require('cors');

var app = express();
const cpu = os.cpus().length;

if (process.env.NODE_ENV !== "production") {
  dotenv.config();
}

const port = process.env.PORT || 3300;

After that add it in App.js

app.use(cors());
app.options("", cors());
app.use(function (req, res, next) 
{
      res.header("Access-Control-Allow-Origin", "");
      res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
      res.header("Access-Control-Allow-Headers","Origin,
      X-Requested-With, X-CallbackType, Content-Type, Accept");
      res.header("Cache-Control", "no-cache");
      if ("OPTIONS" == req.method) 
      {
          res.send(200);
      }
      else 
     {
       next();
     }
});

Restart the app.

You’re all set now to tackle any Access-Control-Allow-Origin errors that come your way!