node.js - 向我的 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
解决方案
origin: `http:localhost:3001`,
似乎错了,缺少反斜杠(//)。否则,您的示例看起来不错,如果我使用您的示例创建一个简单的服务器,它就可以工作。
如果还是不行,可以尝试清除缓存。github中出现问题:https ://github.com/expressjs/cors/issues/159
推荐阅读
- spring - 有没有办法将另一个表中的某些字段作为对象存储到实体中?
- java - Checkmarx 修复 CGI_Stored_XSS 漏洞
- javascript - 减少 React / MERN Stack Bundle 的大小 - 主要是删除重复的 D3
- arrays - 使用 foreach() 循环文件;打印前需要删除重复的结果
- sql - 从用户定义函数中的字符串转换日期和/或时间时转换失败
- emacs - 复制到剪贴板时提示“drag-mouse-1 is undefined”
- assembly - 如何使用存储在堆栈中的地址更改变量的值?
- shell - jar 和 find 命令
- laravel - 处理动态创建的 Laravel 队列
- javascript - 做一个 Ngfor 以避免访问对象的每个属性 - 角度