【问题标题】:AngularJS How to include header in Http requestAngularJS如何在Http请求中包含标头
【发布时间】:2013-10-27 20:32:41
【问题描述】:

我是 angularjs 的新手。我正在尝试发出需要授权的 API 请求。我已将它包含在请求的标头中,但它仍然无法正常工作。我确定我的访问令牌正在工作。有什么建议吗?

$scope.fetch = function() {
    $scope.code = null;
    $scope.response = null;
    $http({
        method: $scope.method,
        url: $scope.url,
        cache: $templateCache,
        headers: {
            Authorization: "access token"
        }
    }).
    success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    }).
    error(function(data, status) {
        $scope.data = data || "Request failed";
        $scope.status = status;
    });
};

【问题讨论】:

标签: angularjs


【解决方案1】:

你可以使用以下

 $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";

它会将上述标头添加到您从应用程序发出的每个 POST 调用中。要添加所有方法通用的标头,请尝试以下操作。

$http.defaults.headers.common['Authorization'] = "Bearer " + user.oauthInfo.access_token;

【讨论】:

  • Anywhere...将此行放入代码的配置部分的最佳方式,或者您甚至可以创建请求拦截器来设置标头
【解决方案2】:

您是否在浏览器的网络请求日志中看到请求的标头?

如果是这样,它是否符合预期的格式?通常,“Authorization”标头前面会有一些内容,例如“Basic”(正如 DevPat 在上面的评论中提到的)或“Bearer”。这里的内容取决于接收请求的后端系统。

预期标题示例:

Authorization: Bearer access_token
Authorization: Basic access_token

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 2019-09-17
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多