我正在尝试使用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的标头。我认为这就是服务器返回错误请求响应的原因。
我正在设置一些其他自定义标头,这些标头在上面的代码中已被省略,它们可以发送并正常显示。
我还应该提到,我可以使用适用于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
(get)。
如果需要,您还可以参考这个SO问题,其中包含有关如何转换数据的更多信息:如何将数据作为表单数据而不是请求有效载荷发布?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句