2016-04-28 168 views
18

我在React-Redux應用程序上創建了2條路線。我已經添加了主頁和回調URL的github應用程序設置。Github oauth的Axios CORS問題未獲取訪問令牌

1. 當你點擊這條路線:https://reduxapp.herokuapp.com/signin 你點擊在Github上登錄按鈕,==>githubGeturi

2. Github上重定向回一個代碼https://reduxapp.herokuapp.com/auth/callback?code=9536286a59228e7784a1githubSendCode('9536286a59228e7784a1 ')動作被觸發

您可以在網絡調用中看到OPTIONS調用通過,但POST調用從未發生。你會得到一個控制檯錯誤:

XMLHttpRequest cannot load https://github.com/login/oauth/access_token?client_id=32b70bf671e04762b26c&…_secret=5851623d94887db7612d4c9bc689310b9d53284b&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 = '5851623d94887db7612d4c9bc689310b9d53284b'; 
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

+0

這是不是這個SO問題的重複? http://stackoverflow.com/questions/14705726/github-api-and-access-control-allow-origin – Clarkie

+0

這是oauth API問題 – STEEL

回答

5

好像你不能讓到終點的呼叫通過JavaScript

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

在您的例子我看到OPTIONS方法調用失敗,這是因爲axios會在你添加額外的頭文件來請求的時候這樣做,但是POST調用也會失敗。

您可以在您的服務器上的應用程序和github之間設置一個代理,該代理只需將您的請求和答覆轉發給您的服務器。

+0

似乎他們不支持實際的Web流量。 – STEEL

+1

@STEEL是的,這是非常愚蠢的 – Burimi

+0

使用本地代理服務器,以使與github ajax呼叫是解決方案。 – STEEL