使用反应返回 405 错误获取快速后端(来自原点'null'已被 CORS 策略阻止:对预检等的响应......)

Posted

技术标签:

【中文标题】使用反应返回 405 错误获取快速后端(来自原点\'null\'已被 CORS 策略阻止:对预检等的响应......)【英文标题】:fetching express back-end with react return 405 error (from origin 'null' has been blocked by CORS policy: Response to preflight etc...)使用反应返回 405 错误获取快速后端(来自原点'null'已被 CORS 策略阻止:对预检等的响应......) 【发布时间】:2020-02-03 06:33:58 【问题描述】:

我有一个小型 express/react 应用程序。我在端口 5000 上运行服务器端,在端口 3000 上运行客户端。我在前端有以下组件:

componentDidMount() 
    fetch('http://localhost:5000/auth/google',
    
          method: 'GET',
          headers: 'Content-Type': 'application/json',
          credentials: 'same-origin',
          'Access-Control-Allow-Origin': '*'
      )
      .then(res =>  
        if (!res.ok) 
          throw res;
        
        return res.json()
      ).then(data => 
        this.setState(loading: false, data);
      ).catch(err => 
        console.error(err);
        this.setState(loading: false, error: true);
      );
  

在后端我有这个:

router.get(
    "/auth/google",
    passport.authenticate("google",  scope: ['Profile','https://www.googleapis.com/auth/analytics.readonly'] )
);

router.get(
    "/auth/google/callback",
    passport.authenticate("google",  failureRedirect: "/error", session: false ),
    function(req, res) 
        var token = req.user.token;
    request('https://www.googleapis.com/analytics/v3/management/accounts?access_token=' + token,  
function (error, response, body) 
  console.log(JSON.parse(body).items);
res.send(JSON.parse(body).items)
);
    
);

这是我遇到的错误:

Failed to load resource: the server responded with a status of 405 ()

Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&scope=Profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&client_id=blablabla.apps.googleusercontent.com' (redirected from 'http://localhost:5000/auth/google') from origin 'null' 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.

【问题讨论】:

【参考方案1】:

CORS 安全违规是由您的浏览器触发的:

已从一台服务器获取 React 代码(可能是脚本包), 看到此代码尝试从另一台服务器获取数据,而该服务器并未告诉浏览器冷静下来并容忍这种安全违规行为。

加载资源失败:服务器响应状态为 405

这意味着浏览器在获取之前尝试联系“另一台服务器”并询问它是否应该容忍安全违规,但“另一台服务器”拒绝交谈。从技术上讲,浏览器已经使用 HTTP 动词 OPTIONS 发送了 HTTP 请求,而服务器则表示它不支持该动词。

在 'https://accounts.google.com/o/oauth2/ 获取获取权限

这是浏览器检测到的实际 CORS 违规,它实际上拒绝执行 fetch。

有很多方法可以让浏览器平静下来,让它容忍违反 CORS 的行为。但最好的办法是确保不会发生违规行为,从而无需放松安全措施。

React 应用程序构建的输出是 .html 文件和脚本包,可能是源映射。称为构建工件。如果您构建您的项目,以便在开发和生产中浏览器从一个单一来源获取所有内容(构建工件、API 响应),例如Express 那么就没有 CORS 问题的余地了。

【讨论】:

您能否更详细地解释最后一部分?构建工件,API 响应?我已经重建了我现在在一台服务器上的应用程序... 最后一部分说如果浏览器从一个服务器下载了 React 应用程序(例如下载了 react 应用程序所包含的文件),然后发送 API 请求并从同一台服务器获取 API 响应,那么就没有可能,没有空间得到 CORS 问题。

以上是关于使用反应返回 405 错误获取快速后端(来自原点'null'已被 CORS 策略阻止:对预检等的响应......)的主要内容,如果未能解决你的问题,请参考以下文章

从 AngularJS POST 到 Django API 以获取 JWT 并返回 405 错误

cURL 未获取预期的 POST 响应 - 错误 405

discord.errors.HTTPException:405 方法不允许(错误代码:0):405:方法不允许

在 PHPMailer 上出现错误 405(不允许)

获取失败并出现错误:POST 415 & GET 405

如何解决错误 405 方法不允许,用于 django graphql 服务器并在前端反应 axios