How to Fix CORS Errors in Node.js APIs

author

By Freecoderteam

Oct 05, 2024

17

image

CORS (Cross-Origin Resource Sharing) errors occur when one domain is making a request to another domain for resources that are not allowed by the server's Access-Control-Allow-Origin policy. Here are some steps you can take to fix CORS errors in Node.js APIs:

  1. Install the cors middleware:
const express = require('express');
const cors = require('cors');
const app = express();

// Enable Cross-Origin requests
app.use(cors());
  1. Set specific domains allowed for CORS requests:
const allowedOrigins = ['http://example1.com', 'http://example2.com'];
const corsOptions = {
  origin: function (origin, callback) {
    if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
};

app.use(cors(corsOptions));
  1. Handle preflight requests:

By default, the cors middleware will allow all methods and headers for any request. If you need to handle preflight requests (OPTIONS method), you can use express-cors package or write your own middleware to handle preflight requests.

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
  1. Check your server logs:

When CORS errors occur, check your server logs for specific error messages. This can help you identify the issue and take steps to fix it.

Popular Tags :
Share this post :

Related Posts

Subscribe to Receive Future Updates

Stay informed about our latest updates, services, and special offers. Subscribe now to receive valuable insights and news directly to your inbox.

No spam guaranteed, So please don’t send any spam mail.