【问题标题】:How do I make a CORS request with fetch on my localhost?如何在本地主机上使用 fetch 发出 CORS 请求?
【发布时间】:2016-03-25 21:00:37
【问题描述】:

我正在构建一个与 GitHub 的 API 集成的 React/Redux 应用程序。此应用程序将要求用户使用 GitHub 的 OAuth 登录。我正在尝试使用 npm 包 isomorphic-fetch 来执行请求,但似乎无法使其正常工作。

这是请求:

require('isomorphic-fetch');
var types = require(__dirname + '/../constants/action_types');

module.exports.handleAuthClick = function() {
  return function(dispatch, getState) {
    var state = getState();

    return fetch('http://localhost:3000/auth')
    .then(function(res) {
        if (res.status <= 200 && res.status > 300) {
          // set cookie
          // return username and token

          return {
            type: HANDLE_AUTH_CLICK,
            data: res.json()
          };
        }
        throw 'request failed';
      })
      .then(function(jsonRes) {
        dispatch(receiveAssignments(jsonRes));
      })
      .catch(function(err) {
        console.log('unable to fetch assignments');
      });
  };
};

这是我的路由器

authRouter.get('/', function(req, res) {
  res.redirect('https://github.com/login/oauth/authorize/?client_id=' + clientId);
});

这是我不断收到的错误

Fetch API cannot load https://github.com/login/oauth/authorize/?client_id=?myclientID
No 'Access-Control-Allow-Origin' header is present on the requested resource.     
Origin 'http://localhost:3000' is therefore not allowed access. If an opaque 
response serves your needs, set the request's mode to 'no-cors' to fetch the 
resource with CORS disabled.

【问题讨论】:

  • 你访问的是 github.com;你可能想要 api.github.com?建议你看看他们的 API 文档。
  • 我收到了您的回复,但是如果您查看 Github OAuth 的 API 文档,您应该重定向到 github.com。 developer.github.com/v3/oauth
  • 嗯...确实。我怀疑这是因为它希望 Web 浏览器 UI 加载页面而不是 API 调用,因此出现 CORS 警告。你有能力呈现一个模态网页视图吗?如果没有,也许 GH 支持隐式授权?
  • 根据文档不支持隐式授权。我将研究一个模态网络视图。我从来没有做过这样的事情,所以我很犹豫。但这可能是我必须走的路。
  • 由于安全原因,几乎所有流行的 OAuth 提供商都转向了这种模式,所以如果你让它工作,这将是一次很棒的学习体验????

标签: ajax node.js reactjs fetch redux


【解决方案1】:

看起来这是一个安全选项,可防止网页向不同域发出 AJAX 请求。我遇到了同样的问题,下面的步骤解决了它。

  1. 首先使用“包管理器”控制台在 WebService 应用中启用 CORS

    PM>Install-Package Microsoft.AspNet.WebApi.Cors  
    
  2. 在App_Start/WebApiConfig.cs文件里面方法Register(HttpConfiguration config)里面添加代码

    config.EnableCors();
    
  3. 最后将 [EnableCors] 属性添加到类中

    namespace <MyProject.Controllers>
    {
        [EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
        public class MyController : ApiController
        {
           //some code
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2021-12-20
    • 2021-05-29
    相关资源
    最近更新 更多