How do I make a CORS request with fetch on my loca

2019-06-02 10:27发布

问题:

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.

Here is the Request:

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');
      });
  };
};

Here is my Router

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

And here is the Error I keep getting

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.

回答1:

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. Firstly enable CORS in the WebService app using 'package Manager' console

    PM>Install-Package Microsoft.AspNet.WebApi.Cors  
    
  2. Inside App_Start/WebApiConfig.cs file inside the method Register (HttpConfiguration config) add code

    config.EnableCors();
    
  3. Finally add the [EnableCors] attribute to the class

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