Home >Web Front-end >JS Tutorial >How to Enable CORS for a Node.js Express Server Communicating with a 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
Import the cors package and the Express module:
const cors = require('cors'); const express = require('express');
Initialize the Express app:
const app = express();
Use the cors middleware to enable CORS for all requests:
app.use(cors());
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' }); });
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'); });
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());
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!