[英]Content-Type header not being set with Angular $http
我正在尝试使用 Angular $http 和以下代码发出跨域 POST 请求。
//I've tried setting and removing these http config options
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
$http.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
//Basic request, with some private headers removed
return $http({
method: 'POST',
//withCredentials:true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
params: params,
url: url
});
预检 OPTIONS 请求获得200 OK
,但随后的 POST 收到400 Bad Request
响应。 查看 Chrome 调试窗口中的跟踪,我没有看到Content-Type: application/x-www-form-urlencoded; charset=UTF-8
POST 的Content-Type: application/x-www-form-urlencoded; charset=UTF-8
标头。 我认为这就是服务器返回错误请求响应的原因。
我正在设置一些其他自定义标头,我在上面的代码中省略了这些标头,并且它们被发送和显示得很好。
我还应该提到,我可以使用 Chrome 的 Advanced Rest Client 应用程序发出此请求并收到正确的响应。 (访问令牌)
我也尝试过直接执行 XMLHttpRequest(),但我遇到了同样的错误。
关于为什么没有设置我的 Content-Type 标头的任何见解?
如果您不发送任何数据,我不确定是否会发送Content-Type
标头。 添加data
对象并尝试:
return $http({
method: 'POST',
//withCredentials:true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: data,
url: url
});
此外,通常在帖子中使用data
而不是params
(获取)。
如果需要,您还可以参考这个 SO 问题,其中包含有关如何转换数据的更多信息: 如何将数据作为表单数据而不是请求有效负载发布?
如果数据属性未定义,则不会将 'Content-Type' 标头添加到请求中,例如,您可以将空字符串作为数据 "" 发送。
var req = {
method: 'GET',
url: '<your url here>',
//headers: {
// 'Content-Type': 'application/json;charset=utf-8'
//},
data: ""
};
$http(req);
我在设置标题时面临同样的问题。 我们需要像这样在$http
请求中发送数据参数
$http({
method: 'POST',
headers: { 'Content-Type': 'application/json},
data: {},
url: url
});
我们也可以发送空白数据。 它会正常工作。
我的问题是我将data
变量设置为对象而不是字符串。
return $http({
method: 'POST',
//withCredentials:true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: {'key1':'value1', 'key2':'value2'},
url: url
});
一旦我将其更改为data:'key1=value1&key2=value2'
它工作正常。 那里还有一个反斜杠,我必须手动输入%5c
代码。
比你非常“Liran B”你的修复对我来说就像一个冠军......问题困扰了我几个小时......
var req = {
method: 'GET',
url: '<your url here>',
//headers: {
// 'Content-Type': 'application/json;charset=utf-8'
//},
data: ""
};
$http(req);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.