AngularJS如何在Http请求中包含头信息

6

我刚开始学习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;
    });
};

在访问令牌之前添加“Basic”。可能是这个问题的重复,这里是链接:https://dev59.com/dmct5IYBdhLWcg3wuPq6 - bp4D
2个回答

5
您可以使用以下内容:
 $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;

无论何处...将此行放入代码的配置部分是最佳方式,甚至您可以创建一个请求拦截器来设置标头。 - vs4vijay

0
你在浏览器的网络请求日志中看到头部了吗?
如果是这样,它的格式是否符合预期?通常,“Authorization”头部会有一些前缀,比如“Basic”(正如DevPat在上面的评论中提到的)或“Bearer”。这里应该填写什么取决于接收请求的后端系统。
预期头部的示例:
Authorization: Bearer access_token
Authorization: Basic access_token

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接