我有一个 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' 访问 XMLHttpRequest at 'http://127.0.0.1:3000/dir' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
我读了很多关于 CORS 的文章,知道这是浏览器方面的问题(Insomnia 完美发送请求)。实际上,我并不清楚我还应该允许什么以及如何允许。基本上我只需要允许标准的 GET、PUT、POST、DELETE 请求。你能指出我代码中的确切配置问题吗?
答案 0 :(得分:-1)
{ Authorization: 'Bearer SomeVeryLongSecretXYZ'}
这样的标头被传递为例如 ...post(url, data, this.headers)
,但必须有 {headers : this.headers}
。fastify.register(require('fastify-cors'), {
origin: '*',
methods: 'GET,PUT,POST,DELETE,OPTIONS',
})