【问题标题】:Preflight request handler arc.codes预检请求处理程序 arc.codes
【发布时间】: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


    【解决方案1】:

    如果不查看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()
      }
    }
    

    这是一些相当人为的伪代码,但我怀疑来自您的 authorization 方法的 return 正在使链短路,这就是预检检查失败的原因。使用next() 继续执行链中的下一个函数应该可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2021-05-11
      • 2014-10-31
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2016-02-17
      相关资源
      最近更新 更多