@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
|
npm install cors |
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.