注意:我沒有足夠的聲望發佈所有鏈接,因此我只刪除了第一個字母,以便文本編輯器不會將其作爲鏈接閱讀。要去他們,請將其粘貼到您的地址欄,並在前面添加h。如何使用JavaScript與OAuth訪問可汗學院API?
我想從可汗學院使用他們的API訪問用戶數據,但是,這是我第一次使用他們的API或AJAX。到目前爲止,我已經設法檢索視頻或練習的數據,但我在使用OAuth檢索用戶數據時遇到了問題。這裏是info on Khan Academy authorization。他們使用OAuth 1.0。這裏是the OAuth library I am using。下面是KA API文檔:http://api-explorer.khanacademy.org/我曾嘗試:
var oauth = OAuth({
consumer: {
public: '****************',
secret: '****************'
},
signature_method: 'HMAC-SHA1'
});
var request_data = {
url: 'http://www.khanacademy.org/api/v1/exercises/logarithms_1',
method: 'GET'
};
$.ajax({
url: request_data.url,
type: request_data.method,
headers: oauth.toHeader(oauth.authorize(request_data))
}).done(function(data) {
alert("done");
});
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
\t "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>KA API Test</title>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.23.1" />
<!-- sha1 -->
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
<!-- sha256 -->
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/enc-base64-min.js"></script>
<script src="oauth-1.0a.js"></script>
<script src="jquery-1.12.0.min.js"></script>
</head>
<body>
</body>
</html>
我自己也嘗試此Javascript使用相同的HTML:
var oauth = OAuth({
consumer: {
public: 'qdMdMjjJQKrwJw2S',
secret: '7XeknfpVBzx8fGMK'
},
signature_method: 'HMAC-SHA1'
});
var request_data = {
url: 'http://www.khanacademy.org/api/v1/exercises/logarithms_1',
method: 'GET'
};
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.khanacademy.org/api/v1/exercises/logarithms_1", true);
xhr.setRequestHeader("Authorization", oauth.toHeader(oauth.authorize(request_data)));
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
for (var key in response) {
console.log(key + ":" + response[key]);
}
alert(response.translated_description_html);
}
}
在控制檯中都出現此錯誤:「XMLHttpRequest無法加載http://www.khanacademy.org/api/v1/exercises/logarithms_1。對預檢請求的響應不會通過訪問控制檢查:請求的資源上不存在「訪問控制 - 允許來源」標頭。 「http://localhost」因此不允許訪問。「
注意:XMLHttpRequest正常工作並返回我想要的內容,然後添加xhr.setRequestHeader("Authorization", "OAuth " + oauth.toHeader(oauth.authorize(request_data)));
。但是,這只是一個不需要授權的測試鏈接,我會更改它後來,
PS我想解決這個錯誤,但我也只需要正確使用OAuth,我想是因爲我沒有使用OAuth之前有錯誤,他們是相關的。
並允許每一個地方,你可以使用: '訪問控制允許來源:*' 作爲通配符項 –
您可以瞭解從以下網址更多: https://developer.mozilla.org/en -US/docs/Web/HTTP/Access_control_CORS –
因此,如果問題是Khan Academy不允許跨源請求,那麼爲什麼程序在添加身份驗證之前工作?這個問題必須與我使用的方式或可汗學院設置OAuth(最有可能是前者)的方式相同。 –