纯Node.js环境下(不使用Express.js)如何实现CORS策略?
Great question! You don’t need Express to handle CORS—you just need to manually manage the right HTTP response headers based on incoming requests. Let me walk you through the core concepts and a working code example.
Core Concepts
CORS relies on the server sending specific response headers to inform browsers that cross-origin requests are permitted. The key headers you’ll work with are:
Access-Control-Allow-Origin: Specifies which origins are allowed (use*for all, or a specific origin likehttps://your-frontend.com)Access-Control-Allow-Methods: Lists allowed HTTP methods (GET, POST, PUT, DELETE, etc.)Access-Control-Allow-Headers: Permits custom request headers (likeContent-Type,Authorization)Access-Control-Allow-Credentials: Set totrueif your app needs to handle cookies or authentication tokens across origins
Basic Implementation
Here’s a minimal vanilla Node.js server that handles CORS for simple requests (GET/POST without custom headers) and preflight OPTIONS requests (sent automatically by browsers for complex requests):
const http = require('http'); const server = http.createServer((req, res) => { // 1. Set core CORS headers for all requests res.setHeader('Access-Control-Allow-Origin', '*'); // Allow all origins (adjust for production!) res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 2. Handle preflight OPTIONS request if (req.method === 'OPTIONS') { res.writeHead(204); // No content needed for preflight responses res.end(); return; } // 3. Handle your actual request logic if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Hello from vanilla Node.js with CORS!' })); } else if (req.method === 'POST') { // Add your POST data handling logic here res.writeHead(201, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'success' })); } else { res.writeHead(404); res.end('Not Found'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
Key Notes for Production
- Avoid
*with credentials: If you need to support cookies or auth tokens, setAccess-Control-Allow-Originto a specific trusted origin (not*) and addres.setHeader('Access-Control-Allow-Credentials', 'true'). - Restrict allowed origins: Instead of allowing all origins, validate the incoming
req.headers.originagainst a list of trusted domains:const allowedOrigins = ['https://your-frontend.com', 'http://localhost:5173']; const origin = req.headers.origin; if (allowedOrigins.includes(origin)) { res.setHeader('Access-Control-Allow-Origin', origin); } - Cache preflight responses: Add
Access-Control-Max-Ageto reduce redundant OPTIONS requests by telling browsers how long to cache preflight results:res.setHeader('Access-Control-Max-Age', '86400'); // Cache for 24 hours
This approach gives you full control over your CORS policy without relying on any frameworks. Let me know if you need help adapting this to your specific use case!
内容的提问来源于stack exchange,提问作者ndm

