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

获取数据时CORS Origin始终为undefined的问题排查

同域Fetch请求下CORS Origin为undefined的问题

问题详情

服务器端CORS配置代码:

import Cors from 'cors';

const cors = Cors({
   methods: ['GET', 'POST', 'HEAD'],
   allowedHeaders: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Api-Authorize, X-Authorize',
   credentials: true,
   origin: (origin, callback) => {
       console.log("*** TESTING", origin);

       return callback(null, true);  // debug, otherwise nothing works
   },
   optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
});

const applyCors = async (req, res) => new Promise((resolve, reject) => {
   cors(req, res, (result) => {
      if (result instanceof Error) {
         reject(result);
      } else {
         resolve(result);
      }
   });
});

export const apiMiddleware = handler => async (req, res) => {
   await applyCors(req, res);

   // ... req is extended with utils    

   return handler(req, res);
};

客户端Fetch请求代码:

const response = await fetch(`/api/data`, {
   credentials: 'same-origin',  // also tried "include"
   headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-Api-Authorize': 'secret'
   },
   method: 'GET'
});

服务器端控制台持续输出:

*** TESTING undefined

查看请求时能看到X-Api-Authorize请求头,但找不到Origin头,请问问题出在哪里?


问题分析与解决

核心原因

浏览器遵循HTTP规范,仅在跨域请求时才会自动发送Origin请求头。你的请求路径是/api/data,属于同域请求(协议、域名、端口与当前页面完全一致),因此浏览器不会附加Origin头,服务器端CORS配置中origin参数自然为undefined,这属于正常行为。

处理方案

  1. 仅同域场景:无需额外修改,当前配置已经允许同域请求(callback(null, true)直接放行所有请求)。
  2. 兼容跨域与同域场景:如果需要同时支持两种请求类型,可以修改origin回调逻辑,显式处理origin为undefined的情况:
origin: (origin, callback) => {
    console.log("*** TESTING", origin);
    // 允许同域请求(origin为undefined)和指定的跨域来源
    const allowedOrigins = ['https://your-approved-domain.com'];
    const isAllowed = origin === undefined || allowedOrigins.includes(origin);
    callback(null, isAllowed);
},
  1. 测试跨域场景:若你是想验证跨域CORS逻辑,需要将请求地址改为跨域地址(例如https://another-domain.com/api/data),此时浏览器会自动发送Origin头,服务器端就能正常获取到对应值。

内容的提问来源于stack exchange,提问作者Yanick Rochon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:45:40