ajax - 如何在本地主机上使用 fetch 发出 CORS 请求?

标签 ajax node.js reactjs fetch redux

我正在构建一个与 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.

最佳答案

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

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

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

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

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

关于ajax - 如何在本地主机上使用 fetch 发出 CORS 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34367692/

相关文章:

node.js - 从strongloop/loopback获取连接数据

php - 如何使用子域和 AJAX 使 PHP session 工作?

javascript - 对每个带有 class/id 的 div 使用 ajax

javascript - 仅当 flask 中的变量发生变化时才更新网站

javascript - 将二进制 NodeJS 缓冲区转换为 JavaScript ArrayBuffer

Javascript React 组件根据条件返回 2 个值

PHP: session 变量丢失, session ID 更改(使用 Ajax)

node.js - 在将它们与 FFmpeg 连接之前如何检查文件是否损坏?

javascript - 如何在控制台中需要 React 组件

javascript - 无法在 react 中导入JSON