Home > Web Front-end > JS Tutorial > How to Enable CORS in Express.js for Node.js Applications?

How to Enable CORS in Express.js for Node.js Applications?

Mary-Kate Olsen
Release: 2024-11-27 16:39:10
Original
223 people have browsed it

How to Enable CORS in Express.js for Node.js Applications?

How to Enable CORS in Express for Node.js

To enable Cross-Origin Resource Sharing (CORS) in Express for Node.js, you can use the cors middleware. This middleware adds the necessary CORS headers to your responses, allowing your application to communicate with other domains or protocols.

Installation

Install the cors middleware using the following command:

npm install cors --save
Copy after login

Usage

After installation, require the cors middleware and use it as follows in your Express app:

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

const app = express();
app.use(cors());
Copy after login

By adding this middleware, all your API routes will automatically have the CORS headers added to their responses.

Customizing CORS Options

You can customize the CORS options by passing a configuration object to the cors() middleware. For example, to enable CORS for all origins, methods, and headers, you can use the following configuration:

app.use(cors({
  origin: '*',
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  allowedHeaders: 'Content-Type,Authorization',
}));
Copy after login

Enabling Preflight Requests

Some browsers may send a preflight request before sending the actual request. To handle this, you can add the preflightContinue option to your CORS configuration:

app.use(cors({
  preflightContinue: true,
}));
Copy after login

Troubleshooting

If you are still encountering CORS issues, make sure that the server is responding with the appropriate CORS headers. You can use tools like Postman or the browser's developer tools to inspect the response headers. Also, ensure that the client-side application is sending the correct origin and credentials.

The above is the detailed content of How to Enable CORS in Express.js for Node.js Applications?. 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