首页 > 解决方案 > 向我的 fetch 请求添加标头会导致 CORS 失败(快速)

问题描述

我正在使用cors库并在我的服务器上具有以下设置(在 上运行localhost:8000):

  cors({
    // Allow requests from these origins :: Access-Control-Allow-Origin
    origin: `http://localhost:8001`,

    // Allow certain headers :: Access-Control-Allow-Headers
    allowedHeaders: [
      "Origin",
      "X-Requested-With",
      "Content-Type",
      "Accept",
      "Authorization"
    ],

    // Allows us to send cookies cross origin :: Access-Control-Allow-Credentials
    credentials: true,

    // Allow this method
    methods: "GET"
  });

当我提出这样的请求时,这很好用:

fetch('http://localhost:8000/api/test', { method: 'GET', credentials: 'include', mode: 'cors' })

但是当我向请求中添加标头时,我在控制台中收到了 CORS 错误:

fetch('http://localhost:8000/api/test', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json' })

我在 Chrome 中遇到的错误是:

Access to fetch at 'http://localhost:8000/api/test' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

唯一的区别是我添加了一个Content-Type标题,但我希望它能够工作,因为它在我的列表中allowedHeaders

标签: node.jsexpresscors

解决方案


  origin: `http:localhost:3001`,

似乎错了,缺少反斜杠(//)。否则,您的示例看起来不错,如果我使用您的示例创建一个简单的服务器,它就可以工作。

如果还是不行,可以尝试清除缓存。github中出现问题:https ://github.com/expressjs/cors/issues/159


推荐阅读