add cors headers to a http server in javascript

To add CORS headers to a Node.js http server, you can use the CORS package. First, install the package using npm:

npm install cors
17 chars
2 lines

Then, in your Node.js http server, require the package and use it as middleware:

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

const server = http.createServer();

server.on('request', (req, res) => {
  // Handle requests here
});

server.use(cors()); // Enable CORS for all routes

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

The cors() middleware will add the necessary CORS headers to every response, allowing cross-origin requests to your server. You can also customize the CORS behavior using the CORS package's options, such as only allowing specific origins or methods.

gistlibby LogSnag