从Angular发送的HTTP请求被发送为OPTIONS而不是POST。
从Angular发送的HTTP请求被发送为OPTIONS而不是POST。
我正在尝试从我的angular.js应用程序向服务器发送一些HTTP请求,但我需要解决一些CORS错误。
HTTP请求使用以下代码进行:
functions.test = function(foo, bar) {
return $http({
method: 'POST',
url: api_endpoint + 'test',
headers: {
'foo': 'value',
'content-type': 'application/json'
},
data: {
bar:'value'
}
});
};
第一次尝试时出现了一些CORS错误。因此,我在我的PHP脚本中添加了以下行:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type');
第一个错误现在已经消除。
现在Chrome的开发者控制台显示以下错误:
angular.js:12011 OPTIONS http://localhost:8000/test (anonymous
function)
423ef03a:1 XMLHttpRequest cannot load
http://localhost:8000/test. Response for preflight has invalid HTTP
status code 400
网络请求看起来和我预期的一样(HTTP状态400也是预期的):
https://i.stack.imgur.com/FmAW9.png
我无法想象如何解决这个问题(以及如何理解),为什么请求会在本地主机上以OPTIONS形式发送,而在远程服务器上以POST形式发送。有没有解决这个奇怪问题的方法?