【问题标题】:Axios CORS issue with Github oauth Not getting access tokenGithub oauth 的 Axios CORS 问题未获取访问令牌
【发布时间】:2016-08-22 19:20:42
【问题描述】:

我在我的 React-Redux 应用程序上创建了 2 个路由。我已经添加了带有主页和回调 URL 的 github 应用程序设置。

1。 当您到达这条路线时:https://reduxapp.herokuapp.com/signin 你点击 Github 登录按钮,==> githubGeturi

2。 Github 使用代码https://reduxapp.herokuapp.com/auth/callback?code=9536286a59228e7784a1 重定向回来 并触发 githubSendCode('9536286a59228e7784a1') 操作

您可以在网络调用中看到 OPTIONS 调用通过,但 POST 调用从未发生。你得到一个控制台错误:

XMLHttpRequest cannot load https://github.com/login/oauth/access_token?client_id=32b70bf671e04762b26c&…_secret=123456789123456789123456789&code=9536286a59228e7784a1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://reduxapp.herokuapp.com' is therefore not allowed access.

下面是我的动作函数:

const CLIENT_ID = '32b70bf671e04762b26c';
const CLIENT_SECRET = '123456789123456789123456789';
const ROOT_URL = window.location.origin;
const REDIRECT_URL = `${ROOT_URL}/auth/callback`;
const AUTHORIZE_URL = 'https://github.com/login/oauth/authorize';
const ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token';
const STATE = _.random(10000);

export function githubGeturi() {
  const GITHUB_URL = `${AUTHORIZE_URL}?client_id=${CLIENT_ID}&scope=user,public_repo&redirect_uri=${REDIRECT_URL}`;

  return (dispatch) => dispatch(signinUrl(GITHUB_URL));
}

export function githubSendCode(code) {
  const GITHUB_URL = `${ACCESS_TOKEN_URL}?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&code=${code}`;

  axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
  const axiosPost = axios.post(
    GITHUB_URL,
    {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'text/json'
    }
  });

  return (dispatch) => {
    dispatch(signinRequest());
    return axiosPost
      .then(
        success => dispatch(signinSuccess(success)),
        error => dispatch(signinError(error))
      );
  };
}

======== 我发现的唯一可能的方法是使用服务器进行 POST 调用。 你可以在这里查看整个解决方案:https://github.com/steelx/ReduxWeatherApp/commit/6215634ca543a4760ea96397fe31b61f22184d91

【问题讨论】:

标签: javascript github oauth cors axios


【解决方案1】:

您似乎无法通过 JavaScript 调用该端点

https://github.com/isaacs/github/issues/330

在您的示例中,我看到 OPTIONS 方法调用失败,这是因为 axios 在您向请求添加额外标头时会这样做,但 POST 调用也会失败。

您可以在您的应用程序和服务器上的 github 之间设置一个代理,它只是转发您的请求并回复响应。

【讨论】:

  • 似乎他们不支持实际的 Web 流。
  • 使用本地代理服务器,通过github进行ajax调用是解决办法。
猜你喜欢
  • 2016-07-18
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多