Home > Web Front-end > JS Tutorial > How to Enable CORS for a Node.js Express Server Communicating with a Different Port?

How to Enable CORS for a Node.js Express Server Communicating with a Different Port?

Susan Sarandon
Release: 2024-11-28 05:48:13
Original
860 people have browsed it

How to Enable CORS for a Node.js Express Server Communicating with a Different Port?

Enabling CORS for Node.js Express Server with Different Port

Background

Cross-Origin Resource Sharing (CORS) allows web applications to securely make requests to resources on other websites. When using Node.js Express server to communicate with another API running on a different port, it's necessary to enable CORS to avoid cross-origin errors.

Enable CORS with Express

To enable CORS in Express, install the cors package:

npm install cors --save
Copy after login

Import the cors package and the Express module:

const cors = require('cors');
const express = require('express');
Copy after login

Initialize the Express app:

const app = express();
Copy after login

Use the cors middleware to enable CORS for all requests:

app.use(cors());
Copy after login

Configure CORS for Specific Routes

If you want to enable CORS only for specific routes, use the following syntax:

app.get('/products/:id', cors(), (req, res, next) => {
  res.json({ msg: 'This is CORS-enabled for a Single Route' });
});
Copy after login

Example

In the provided example, you want to enable CORS on port 8080, where dcm4chee runs. To do this, assume you have the following code in your Node.js app:

const express = require('express');
const app = express();

app.get('/request-from-browser', (req, res, next) => {
  // Your code to handle the request
});

app.listen(3000, () => {
  console.log('Node.js app listening on port 3000');
});
Copy after login

To enable CORS for the /request-from-browser route on port 8080, add the following middleware before the route code:

app.use('/request-from-browser', cors());
Copy after login

This will enable CORS for requests made to /request-from-browser on port 8080.

The above is the detailed content of How to Enable CORS for a Node.js Express Server Communicating with a Different Port?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template