【发布时间】:2021-03-21 07:59:04
【问题描述】:
我有一个 Vue 前端、一个 Auth0 和 Fastify 后端。 CORS配置如下:
fastify.register(require('fastify-cors'), {
origin: 'http://localhost:8080',
methods: 'GET,PUT,POST,DELETE,OPTIONS,HEAD',
allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept',
})
前端头配置:
this.$auth.getTokenSilently().then(token => {
this.headers = {
Authorization: `Bearer ${token}` // send the access token through the 'Authorization' header
};
问题很常见:
从源“http://localhost:8080”访问“http://127.0.0.1:3000/dir”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我已经阅读了很多关于 CORS 的内容,知道这是浏览器方面的问题(Insomnia 可以完美地发送请求)。实际上,我还不清楚我还应该允许什么以及如何允许。基本上我只需要允许的标准 GET、PUT、POST、DELETE 请求。您能否指出我的代码中的确切配置问题?
【问题讨论】:
-
Access-Control-Allow-Origin: 127.0.0.1:3000,您是否尝试为您有问题的来源授予访问权限?
-
Access-Control-Allow-Origin: * - 这将允许访问来自任何来源的任何请求
-
我试过*,其实是以前的。也不行。但我读过必须有一个明确的来源配置。尝试访问 API 端点的 Origin 是 8080,而不是 3000。
-
origin: (origin, cb) => { if(/localhost/.test(origin)){ // 来自 localhost 的请求会通过 cb(null, true) return } // 产生错误在其他来源上,禁用访问 cb(new Error("Not allowed")) } 您是否尝试过来自 doc 的代码?
-
同样的结果