【问题标题】:CORS origin always undefined when fetching data获取数据时 CORS 来源始终未定义
【发布时间】:2022-12-12 23:59:46
【问题描述】:

使用这个服务器配置

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);
};

还有一个客户像这样获取请求

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'
});

服务器console.log总是印刷

*** 测试未定义

检查请求时,我看到了 X-Api-Authorize 标头,但没有看到 Origin。少了什么东西?

【问题讨论】:

  • 'Content-Type': 'application/json',method: 'GET' 结合使用时毫无意义。 GET 请求没有正文,所以正文不能是 JSON。

标签: javascript cors fetch


【解决方案1】:
fetch(`/api/data`

这是一个相对 URL,因此您正在发出同源请求。

origin 标头仅包含在跨域请求中。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2016-11-03
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多