将标题授权设置为角度$http发布



我想在 Angular js 中对 $http.post 请求的标头设置授权。

在简单的HTML Ajax上,它可以工作:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) { //do something 
  }
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Authorization", "xxxxxxxxxx");
xhttp.send();

在角度上,我收到一条错误消息 - "Cannot read property 'protocol' of undefined"

var configHeader = {
  headers: {
    'Authorization': 'xxxxxx'
  }
};
$http.post(url, configHeader).then(function(response) {
  //do something 
});

请帮忙。

$http.post有3个参数:

  • 网址
  • 数据
  • 配置(可选(

您缺少要发布的数据...

示例角度请求:

var req = {
method: 'POST',
url: 'http://example.com',
headers: {
Content-Type': undefined
},
data: { test: 'test' }
}

我猜,你的配置标头应该configHeader: {'Authorization': 'xxx'}

根据文档

var configHeader = {
  headers: {
    'Authorization': 'xxxxxx'
  }
};
$http.post(url, {}, configHeader).then(function(response) {
  //do something 
});

终于找到了答案!

chrome 中存在一些错误,仅当您在开发人员工具上使用断点时才会创建此错误。我删除了断点,此错误再也没有出现在控制台上。

仅供参考 - 这是我删除断点之前在 chrome 控制台上显示的错误:

在此处输入图像描述

最新更新