Using cors with Non-Express Frameworks

If you’re using other HTTP frameworks or libraries, you’ll need to manually handle CORS. Here’s a brief example using http module:

const http = require('http');

const server = http.createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  
  if (req.method === 'OPTIONS') {
    res.writeHead(204); // No content
    res.end();
    return;
  }

  // Your usual request handling here
  res.end('Hello World');
});

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *