add cors headers to a http server with a specific origin in javascript

To add CORS headers to a HTTP server with a specific origin in JavaScript, you can use the cors package.

First, install the package by running the following command in your terminal:

index.tsx
npm install cors
17 chars
2 lines

Then, in your JavaScript code, require the cors package and add it as middleware to your HTTP server:

index.tsx
const http = require('http');
const cors = require('cors');

const server = http.createServer((req, res) => {
  // Your server logic here
});

const corsOptions = {
  origin: 'http://example.com' // Replace with your origin
};

server.use(cors(corsOptions));

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});
343 chars
17 lines

In the example above, the corsOptions object specifies that the server should only allow requests from http://example.com. You can replace this value with your own origin.

By adding the cors middleware to your server, it will automatically handle preflight requests and set the appropriate CORS headers for all incoming requests from the allowed origin.

gistlibby LogSnag