繁体   English   中英

将标题授权设置为有角$ http post

[英]set header authorization to angular $http post

我想在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 
});

请帮忙。

根据文档

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应该是configHeader: {'Authorization': 'xxx'}

终于我找到了答案!

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

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

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM