【问题标题】:When setting http authorization headers the AngularJS app crashes设置 http 授权标头时,AngularJS 应用程序崩溃
【发布时间】:2014-06-04 14:09:06
【问题描述】:

我想向 twitter api 发出请求并获取当前登录的用户源。

我用“apigee”尝试了 twitter api,一切正常。即使将 Authorization 标头从“apigee”复制到“postman”,我也会取回数据。

但是当我尝试在我的 angular-app 中发出 http-request 时,整个应用程序停止工作。 在浏览器中只有输出“{{message}}”,控制台打印两条错误消息:

Uncaught SyntaxError: Unexpected identifier :3000/javascripts/app.js:211
Uncaught Error: No module: app angular.min.js:17

我的应用程序中的代码如下所示

app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url, 
{headers: {
  'Authorization':
  Oauth oauth_consumer_key = "xxxx",
  oauth_signature_method="HMAC-SHA1"
  oauth_timestamp="1401883718",
  oauth_nonce="840988792",
  oauth_version="1.0",
  oauth_token="xxxx",
  oauth_signature="xxx"
}})
.then(function (data) {
$scope.data = data.data;
console.log(data);
});

谁能帮助我或告诉我我做错了什么。 凯文

【问题讨论】:

  • 这可能是因为无效的javascript。将您的授权值封装在一个字符串中。
  • 我尝试了所有可能的与引号相关的方法,例如删除引号、替换为单引号、用双引号/单引号括起来,但没有任何效果。
  • 一个javascript字符串只能在一行。一个很好的反击它使用['something', 'something else'].join('')

标签: angularjs angularjs-resource angular-http angularjs-authentication


【解决方案1】:

试试这个方法:

app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url, {
    headers: {
        'Authorization':
            'Oauth oauth_consumer_key = "xxxx",' +
            'oauth_signature_method="HMAC-SHA1",' +
            'oauth_timestamp="1401883718",' +
            'oauth_nonce="840988792",' +
            'oauth_version="1.0",' +
            'oauth_token="xxxx",' +
            'oauth_signature="xxx"'
    }
}).then(function (data) {
    $scope.data = data.data;
    console.log(data);
});

【讨论】:

  • 这种方式工作得非常好。谢谢。现在我收到 400 bad request 错误,但可能只是参数有问题。
猜你喜欢
  • 2015-12-02
  • 1970-01-01
  • 2015-09-27
  • 2017-04-17
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 2016-05-30
相关资源
最近更新 更多