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:
- Install the cors middleware:
const express = require('express');
const cors = require('cors');
const app = express();
// Enable Cross-Origin requests
app.use(cors());
- 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));
- 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();
});
- 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.