我如何通过本地主机发出带有获取的CORS请求? [英] How do I make a CORS request with fetch on my localhost?

查看:59
本文介绍了我如何通过本地主机发出带有获取的CORS请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a React/Redux app that integrates with GitHub's API. This app will require users to sign-in using GitHub's OAuth. I'm trying to use the npm package isomorphic-fetch to do the request but cannot seem to get it to work.

这是请求:

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.

推荐答案

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

Looks like this is a security option which prevents a web page from making AJAX requests to different domain. I faced the same problem, and below steps fixed it.

  1. 首先使用程序包管理器"控制台在WebService应用中启用CORS

  1. Firstly enable CORS in the WebService app using 'package Manager' console

PM>Install-Package Microsoft.AspNet.WebApi.Cors  

  • 在方法Register(HttpConfiguration配置)内部的App_Start/WebApiConfig.cs文件中添加代码

  • Inside App_Start/WebApiConfig.cs file inside the method Register (HttpConfiguration config) add code

    config.EnableCors();
    

  • 最后将[EnableCors]属性添加到该类

  • Finally add the [EnableCors] attribute to the class

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

  • 这篇关于我如何通过本地主机发出带有获取的CORS请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆