首页 > 解决方案 > 预检请求处理程序 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 的对象

我已经尝试并学到了什么:

我可以做些什么来在我的后端处理这些预检请求?我是否必须为我当前的所有端点编写一个 OPTIONS 请求处理程序?有没有办法禁用预检请求?可以禁用预检请求吗?我是否错过了另一件重要的事情并使这一点过于复杂?

标签: node.jscorshttprequestpreflightarchitect

解决方案


如果不查看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()继续执行链中的下一个功能应该可以解决您的问题。


推荐阅读