我如何使用本地主机上的提取进行CORS请求?

我正在构build一个与GitHub的API集成的React / Redux应用程序。 这个程序将要求用户使用GitHub的OAuthlogin。 我试图使用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. 

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

  1. 首先使用“包pipe理器”控制台在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