AngularJS:Http标题

时间:2017-05-19 08:30:41

标签: angularjs http

我是angularJS的新手。我想在我的http请求中添加标题,但我不明白如何?到目前为止,我已经写了这段代码。

没有标题的原始代码:

function saveUser(user, $http) {
        var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";

        var url = __apiRoot + "/users/" + user.id;
        var dataObj = {
            payload: JSON.stringify(user),
            _method: "PUT",
        }
        return $http.post(url, dataObj);
    }

现在我正在为它添加标题,代码变成这样:

function saveUser(user, $http) {
        var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";

        var url = __apiRoot + "/users/" + user.id;
        var dataObj = {
            payload: JSON.stringify(user),
            _method: "PUT",
        }
        return $http({headers: {
                'Authorization': token
            }}).post(url, dataObj);
    }

通过添加标头,我收到此错误:

  

angular.js:14525错误:[$ http:badreq] Http请求配置网址   必须是字符串或$ sce可信对象。收到:未定义

1 个答案:

答案 0 :(得分:0)

您使用了错误的语法。请查看$http here的角度文档。

您的代码应如下所示:

$http({
      method: 'POST',
      url: __apiRoot + "/users/" + user.id,
      data: JSON.stringify(user)
      headers: {
       'Authorization': token
      }
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
      }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });