CORS Headers
NodeJS
Medium
3 views
Problem Description
Add simple CORS headers for GET requests.
Output Format
Start server code.
Constraints
Allow any origin for demo.
Official Solution
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
res.writeHead(204);
return res.end();
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ site: 'meetcode' }));
});
server.listen(3003, () => console.log('http://localhost:3003'));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!