node.js - 预检请求处理程序 arc.codes
问题描述
从反应页面向使用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
/get-api-contractormonths 处的 index.js 文件
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 标头(在前面)时,它可以工作了!
- 这可能与浏览器发出的预检请求有关(当它是一个没有标头的简单 GET 时,它不会发送预检请求,但在使用 auth 标头时会发送)
- 预检请求正在向我的后端发送一个 OPTIONS 请求,我可以确认这一点,因为在我的后端添加 OPTIONS 请求处理程序会获取请求而不是 GET 处理程序
我可以做些什么来在我的后端处理这些预检请求?我是否必须为我当前的所有端点编写一个 OPTIONS 请求处理程序?有没有办法禁用预检请求?可以禁用预检请求吗?我是否错过了另一件重要的事情并使这一点过于复杂?
解决方案
如果不查看authorization
函数的代码,很难判断,但这就是问题的根源所在。您在问题中提到:
授权函数还返回一个具有属性 cors: true 的对象
但您实际上并不想从此函数返回对象,除非您未通过身份验证步骤。
示例授权方法可能如下所示:
module.exports = async function auth (req, res, next) {
// Do the OAuth Dance
const oauth = oauthDance()
if (!oauth.authenticated) {
return {
status: 401,
json: { errors: [ 'authorization_failed' ] }
}
} else {
// Oauth succeeded so let's add the token to the request
// for the next function in the chain
req.token = oauth.token
next()
}
}
这是一些非常人为的伪代码,但我怀疑return
你的authorization
方法是短路链,这就是预检检查失败的原因。用于next()
继续执行链中的下一个功能应该可以解决您的问题。
推荐阅读
- powerbi - 在 DAX 中,如何创建一个表变量来删除用户选择的过滤器之一?
- bluetooth - 在 Raspberry Pi 上将 BlueZ 升级到 5.52
- python - 如何使用具有非线性约束的 LMFIT 解决最小二乘问题?
- c# - C#如何使用LINQ获取有条件的子集合项的数量
- c++ - 将数据从一个阵列存储到另外两个阵列中不起作用
- javascript - React Redux onClick 调用操作创建者不工作
- java - Spring Boot Web 应用程序未检测到控制器
- android - Android 房间在第一次通话时不返回任何数据
- python - 如何在内存中执行 sqlalchemy、sqllite 中的存储过程?
- python - 连接不同格式的 YARA 规则