How to enable cors in node.js https server?

Member

by lily , in category: PHP General , 4 months ago

How to enable cors in node.js https server?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 4 months ago

@lily 

To enable CORS in a Node.js HTTPS server, you can use the cors middleware package. Here is how you can do it:

  1. First, install the cors package by running the following command in your Node.js project directory:
1
npm install cors


  1. In your Node.js server file, require the cors package and use it as middleware before your route handlers. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');
const cors = require('cors');
const https = require('https');
const fs = require('fs');

const app = express();

// Enable CORS for all requests
app.use(cors());

// Your route handlers
app.get('/api/data', (req, res) => {
  res.json({ message: 'Hello, World!'});
});

// Set up the HTTPS server
const options = {
  key: fs.readFileSync('path/to/your/private-key.pem'),
  cert: fs.readFileSync('path/to/your/certificate.pem')
};

https.createServer(options, app).listen(443);


In this example, the cors() function is used as middleware to enable CORS for all requests. You can also configure the CORS options by passing an object to the cors() function. For example, to allow only specific origins, you can pass the origin option:

1
2
3
app.use(cors({
  origin: 'https://example.com'
}));


By using the cors middleware in your Node.js HTTPS server, you can easily enable CORS and allow cross-origin requests from your client-side applications.