Cross-Origin Resource Sharing (CORS) is a security feature of the modern web that prevents websites from making requests across different domains. In Node.js, you can fix CORS issues by using middleware libraries like cors
.
Here's an example of how to use cors
in your Express.js application:
- First, install the
cors
package if you haven't already:
npm install cors
- Then, require and use it in your server file (e.g.,
server.js
) like this:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
// Your routes go here...
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
If you need to customize the CORS behavior, you can pass an options object to cors()
:
const cors = require('cors');
app.use(cors({
origin: 'http://example.com', // Allow requests from this origin only
methods: ['GET', 'POST'], // Allow these methods only
allowedHeaders: ['Content-Type'] // Allow these headers only
}));
If you want to allow all origins (not recommended in production), you can use '*'
as the value for origin
.
That's it! With this setup, your Express.js application will be CORS-compliant and will handle requests from any origin by default.