【问题标题】:Enabling CORS on StrongLoop backed ReactJS application在 StrongLoop 支持的 ReactJS 应用程序上启用 CORS
【发布时间】:2017-02-20 12:23:03
【问题描述】:

我有一个配置了 Passport 的环回 API 服务器,在端口 3000 上运行。我的 UI 由从端口 3080 提供服务的 react JS 组成。我想通过 Google 实现身份验证。为此,从我的反应应用程序中,我正在调用 localhost:3000/auth/google 但是由于 CORS 错误,呼叫没有被重定向到谷歌:

Fetch API cannot load http://localhost:3000/auth/google. Redirect from 'http://localhost:3000/auth/google' to 'https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=h…d=584602753475-1kk345gd8trcn31pbg1v2gncajhpakk8.apps.googleusercontent.com' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.

当我从新的浏览器选项卡中点击http://localhost:3000/auth/google url 时,一切正常。

谁能告诉我应该在哪里启用 cors ?

编辑

我可以看到,浏览器正在向 localhost:3000/auth/google 发出选项请求

这是我使用 curl 发出选项请求时得到的: HTTP/1.1 204 No Content X-Powered-By: Express Vary: Origin Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE Access-Control-Max-Age: 86400 Date: Mon, 20 Feb 2017 14:05:53 GMT Connection: keep-alive

【问题讨论】:

    标签: reactjs strongloop


    【解决方案1】:

    我不知道如何在 Strongloop 或 ReactJS 中启用 CORS,但要启用它,您需要两件事:

    1. The right configuration of the JS request like so:
    
    var params = {
      …
      mode: 'cors',
      credentials: 'include' //<- that gave me some headache a while ago,
                             //but is probably not necessary in your case. 
      …
    }
    
    fetch(new Request(<url>, params).then(res => …);
    
    1. 正确的服务器配置。 cors 请求将首先使用预检请求调用服务器,该请求应该告诉浏览器它是否可以访问该资源,包括所有标头。此请求使用 http OPTIONS 方法/动词,因此您的服务器需要正确响应。如果是这样,浏览器将执行您想要执行的实际请求。

    希望对你有帮助。

    【讨论】:

    • 感谢您的回复。我的 JS 获取请求中有这一部分。浏览器向 http://localhost:3000/auth/google 发出 Options 请求。这就是事情被阻止的地方。
    • 您是否测试了选项请求? stackoverflow.com/questions/14481850/…
    • 我尝试了一个选项请求。回复是:HTTP/1.1 204 No Content X-Powered-By: Express Vary: Origin Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE Access-Control-Max-Age: 86400 Date: Mon, 20 Feb 2017 14:05:53 GMT Connection: keep-alive
    • 我猜缺少允许的content-type 的标头。正在尝试发布/接收 json?
    • 那个enpoint返回一个内容类型为text/html的html页面;
    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 2020-09-06
    • 2013-06-16
    • 2012-12-26
    • 1970-01-01
    • 2013-12-26
    • 2013-02-03
    • 2018-02-06
    相关资源
    最近更新 更多