1

我正在尝试向 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
4

1 回答 1

4

您正在从浏览器发送跨域 ajax 请求,出于安全原因,这通常是不允许的。您必须从您的服务器而不是客户端的浏览器发送请求。

于 2013-07-20T12:47:50.893 回答