预检请求处理程序 arc.codes

问题描述

在从 React 页面向使用 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 请求处理程序?有没有办法禁用预检请求?可以禁用预检请求吗?我是不是遗漏了另一件重要的事情并且把它复杂化了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)