You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯Node.js环境下(不使用Express.js)如何实现CORS策略?

Implementing CORS in Vanilla Node.js (No Express)

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 like https://your-frontend.com)
  • Access-Control-Allow-Methods: Lists allowed HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Access-Control-Allow-Headers: Permits custom request headers (like Content-Type, Authorization)
  • Access-Control-Allow-Credentials: Set to true if 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, set Access-Control-Allow-Origin to a specific trusted origin (not *) and add res.setHeader('Access-Control-Allow-Credentials', 'true').
  • Restrict allowed origins: Instead of allowing all origins, validate the incoming req.headers.origin against 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-Age to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:12:32