与Github oauth的Axios CORS问题没有获得访问令牌

STE*_*EEL 21 javascript oauth github cors axios

我在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.
Run Code Online (Sandbox Code Playgroud)

以下是我的行动功能:

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))
      );
  };
}
Run Code Online (Sandbox Code Playgroud)

========我找到的唯一可行方法是与服务器进行POST调用.您可以在此处查看整个解决方案:https://github.com/steelx/ReduxWeatherApp/commit/6215634ca543a4760ea96397fe31b61f22184d91

Bur*_*imi 6

看起来你无法通过JavaScript调用那个终点

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

在您的示例中,我看到OPTIONS方法调用失败,这是因为axios在您为请求添加额外标头时执行此操作,但POST调用也失败.

您可以在服务器上的应用程序和github之间设置代理,只需转发您的请求并回复响应即可.