Angularjs 将自定义访问令牌作为http请求发送

Angularjs 将自定义访问令牌作为http请求发送,angularjs,ajax,api,oauth,Angularjs,Ajax,Api,Oauth,我想使用oauth身份验证将api与mvc站点连接起来。 为此,我需要通过http请求发送访问令牌,如下所示 addPostComment: function addPostComment(postid, UserId, comment, accessToken) { var request = $http({ method: "post", url: apiPath.addPost

我想使用oauth身份验证将api与mvc站点连接起来。 为此,我需要通过http请求发送访问令牌,如下所示

addPostComment: function addPostComment(postid, UserId, comment, accessToken) {

                var request = $http({
                    method: "post",
                    url: apiPath.addPostComment,
                    data: {
                        SocialPostId: postid,
                        CommentDescription: comment,
                        CommentedUserId: UserId,
                        CommentedDate: new Date()
                    },
                    params: {
                        action: "post"
                    },                   
                    beforeSend: function (xhr) {

                        xhr.setRequestHeader('Authorization', 'bearer ' + accessToken);
                    }
                });
                return (request.then(handleSuccess, handleError));
            }
参数accessToken有值。但当我设置为请求头时,它总是说Authorization:Bearer undefined

有人能告诉我这个代码有什么问题吗

    $http({
      method: "post",
                url: apiPath.addPostComment,
                data: {
                    SocialPostId: postid,
                    CommentDescription: comment,
                    CommentedUserId: UserId,
                    CommentedDate: new Date()
                },
                params: {
                    action: "post"
                }, 
      headers: {
      'Authorization': 'bearer ' + accessToken
      }
    });

您可以像这样发送HTTP请求

可能您可以直接说头:{'Authorization':'bearer'+accessToken},而不是在发送前添加它们。。据我所知,在angularjs“$http”中,如果没有拦截器,您无法使用beforeSend。是的,它工作正常。但我想在请求发送之前更新它的头,所以我使用这个方法。在这段代码中,apipath是常量。angular.module(“test”).constant('apiPath',{'accessToken':“eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyjuyw1lawqiiiiiiiwid5pcxvlx25hbwuiiijzdxblcmfkbwludx”。如果我在这个常量中设置accessToken并像以前一样在服务中使用发送:函数(xhr){xhr.setRequestHeader('Authorization','bear'+apiPath.accessToken);}。它工作正常。如果我使用param token,它为什么不工作?如果我使用常量token,它为什么工作。嗨,Adem,实际上我声明了const bearerToken=accessToken,并在beforeSend函数中使用它,它只在post方法中工作正常。如果我在get方法中使用相同的概念,它就不工作。http请求作为承载者发送授权定义。任何人都知道这其中的实际问题是什么以及如何解决这个问题?如果您想更新标头,只需使用服务获取访问令牌,并通过调用代码中的方法获取访问令牌,`headers:{`
'Authorization':'Bearner'+yourService.getAccessToken()
}
并将您的服务添加为依赖项,将解决您的问题。因此,您将在所有请求中获得更新的访问令牌。。