【发布时间】:2021-09-26 00:28:03
【问题描述】:
当我从反应页面向使用arc.codes 框架运行的后端发出请求时,我遇到了一个奇怪的 cors 错误。 这是完整的错误:
Access to fetch at 'http://localhost:3333/api/endpoint' from origin 'http://localhost:3000' 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.
我发出请求的前端代码如下:
const options = {
method: 'GET',
headers: {
'Authorization':'Bearer token'
},
};
const response = yield call( fetchJSON, `${process.env.REACT_APP_BACKEND_URL}/contractormonths`, options );
处理请求的后端代码:
.arc 清单文件:
@app
my-app
@http
get /api/contractormonths
index.js 文件位于 /get-api-contractormonths
const arc = require('@architect/functions');
const { authorization } = require('@architect/shared/oauth');
async function route(request){
return {
cors: true,
json: {'message':'Hello world!'}
};
}
exports.handler = arc.http.async(authorization, route);
授权函数还返回一个具有属性 cors: true 的对象
我已经尝试和学到的:
- 我认为请求没有到达后面的 GET 处理函数
- 当我删除 auth 中间件(在后面)和 auth 标头(在前面)时,它可以工作了!
- 这可能与浏览器生成的preflight request 有关(当它是一个没有标头的简单 GET 时,它不会发送预检请求,但在使用 auth 标头时会发送)
- 预检请求正在向我的后端发送一个 OPTIONS 请求,我可以确认这一点,因为在我的后端添加 OPTIONS 请求处理程序会获取请求而不是 GET 处理程序
如何在后端处理这些预检请求?我是否必须为我当前的所有端点编写一个 OPTIONS 请求处理程序?有没有办法禁用预检请求?可以禁用预检请求吗?我是否遗漏了另一件重要的事情并且过于复杂了?
【问题讨论】:
标签: node.js cors httprequest preflight architect