简体   繁体   English

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

[英]set header authorization to angular $http post

i want to set an authorization on the header of $http.post request in angular js. 我想在angular js的$ http.post请求的标头上设置授权。

on simple html ajax it works: 在简单的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();

On angular I get an error message - "Cannot read property 'protocol' of undefined" 在角度上,我收到一条错误消息- "Cannot read property 'protocol' of undefined"

var configHeader = {
  headers: {
    'Authorization': 'xxxxxx'
  }
};

$http.post(url, configHeader).then(function(response) {
  //do something 
});

please help. 请帮忙。

As per documentation 根据文档

var configHeader = {
  headers: {
    'Authorization': 'xxxxxx'
  }
};

$http.post(url, {}, configHeader).then(function(response) {
  //do something 
});

$http.post has 3 parameters: $http.post具有3个参数:

  • url 网址
  • data 数据
  • config (optional) 配置(可选)

You're missing the data to post... 您缺少要发布的数据...

Sample angular request: 角度要求样本:

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

I am guessing, your configHeader should be configHeader: {'Authorization': 'xxx'} 我猜,您的configHeader应该是configHeader: {'Authorization': 'xxx'}

Finally I found the answer! 终于我找到了答案!

There is some bug in chrome that create this error only when you using break point on the developer tool. chrome中有一些错误,仅当您在开发人员工具上使用断点时才会产生此错误。 I removed the break point and this error never appeared again on the console. 我删除了断点,此错误再也没有出现在控制台上。

FYI - this is the error which has been displayed on the chrome console before I had removed the break point: 仅供参考-这是我删除断点之前在chrome控制台上显示的错误:

enter image description here 在此处输入图片说明

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

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