How to Fix Cross-Origin Resource Sharing (CORS) in Node.js

author

By Freecoderteam

Oct 05, 2024

17

image

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:

  1. First, install the cors package if you haven't already:
npm install cors
  1. 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.

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.