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

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

const server = http.createServer((req, res) => {
  // Set CORS headers
  res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
  res.setHeader('Access-Control-Request-Method', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  // Return response
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
500 chars
17 lines

In the above example, we create a basic HTTP server using Node.js http module. The CORS headers are set by calling res.setHeader() on the server response object.

The 'Access-Control-Allow-Origin' header sets the origin (in this example, http://example.com) that is allowed to access the server.

The 'Access-Control-Request-Method' header specifies the HTTP methods (in this example, GET and POST) that are allowed for CORS requests.

The 'Access-Control-Allow-Headers' header specifies the allowed request headers.

Finally, we send a simple response back to the client, specifying the content type as 'text/plain'.

Note that this is a very basic example and does not provide any security or authentication for the client/server communication.

gistlibby LogSnag