【发布时间】:2013-07-20 20:47:50
【问题描述】:
我正在尝试向 twitter 发送仅应用程序的身份验证请求以获取 access_token。我编写了一个 javascript 代码
函数 getTwitterAuthorizeTokens() { 返回{oauth_token:“abcdefg”,oauth_token_secret:“asdfasdfasfdasdf”}; }
// Get the consumer key and secret
function getTwitterConsumerTokens() {
return {key: "xxxxxxxxxxxxxxxxx", secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"};
}
var s = encodeURIComponent(getTwitterConsumerTokens().key,'RFC 1738');
s += ':'+encodeURIComponent(getTwitterConsumerTokens().secret,'RFC 1738');
$( document ).ready(function(){
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic "+s);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
},
url: "https://api.twitter.com/oauth2/token",
data: "grant_type=client_credentials",
processData: false,
success: function(msg) {
alert("successfull");
}
});
当这个脚本被加载时。它在控制台中给了我错误
OPTIONS https://api.twitter.com/oauth2/token 405 (Method Not Allowed) sinon-server-1.7.1.js:573
apply sinon-server-1.7.1.js:573
fakeXhr.(anonymous function) sinon-server-1.7.1.js:592
send jquery.min.js:4
f.extend.ajax jquery.min.js:4
(anonymous function) index.html:143
e.resolveWith jquery.min.js:2
e.extend.ready jquery.min.js:2
c.addEventListener.C jquery.min.js:2
XMLHttpRequest cannot load https://api.twitter.com/oauth2/token. Origin null is not allowed by Access-Control-Allow-Origin. index.html:1
如何解决此错误请指导。我正在关注这个链接https://dev.twitter.com/docs/auth/application-only-auth
当我使用 node.js 托管它时,它给了我错误
Failed to load resource: the server responded with a status of 405 (Method Not Allowed) https://api.twitter.com/oauth2/token?jsonp=success
XMLHttpRequest cannot load https://api.twitter.com/oauth2/token?jsonp=success. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin. index.html:1
【问题讨论】:
-
encodeURIComponent函数有第二个参数有什么意义? -
你是从文件系统还是服务器运行它?
-
在你应该使用 RFC 1738 对参数进行编码的链接 (dev.twitter.com/docs/auth/application-only-auth) 中,它现在给出的结果与提供的相同,但将来会改变。
-
来自文件系统的@vsr。
-
@RiteshMehandiratta 这一定是问题所在。将其托管在服务器上(如 apache 或 nginx)并尝试。 stackoverflow.com/questions/8456538/…
标签: javascript jquery twitter cors