我正在使用 angular JS 将一些数据发送到 nodejs 服务器。
当我使用 curl 时,我取回了我发送的数据(正确结果):
curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" 'http://127.0.0.1:3000/s?table=register_rings&uid=1'
> {"MyKey":"My Value"}
但是,当我使用angularjs服务时,出现了错误。
.factory('RegisterRingsService', function($http, $q) {
// send POST request with data and alert received
function send(data, uid) {
$http({
method: 'POST',
url: 'http://127.0.0.1:3000/s?table=register_rings&uid=1',
data: '{"MyKey":"My Value"}',
headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin":"*"},
responseType: 'json'
}).success(function(data, status, headers, config) {
alert('success', data, status);
}).error(function(data, status, headers, config) {
alert('error' + JSON.stringify(data) + JSON.stringify(status));
}).catch(function(error){
alert('catch' + JSON.stringify(error));
});
}
return {send : send};
})
错误如下:
{"data":null,"status":0,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://127.0.0.1:3000/s?table=register_rings","data":"{\"MyKey\":\"My Value\"}","headers":{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","Accept":"application/json, text/plain, */*"},"responseType":"json"},"statusText":""}
我怀疑我应该插入 CORS header ,但我不确定该怎么做。
任何帮助将不胜感激
最佳答案
问题在于您如何将数据传输到服务器。这是因为 jQuery 和 Angular 对数据的序列化方式不同。
默认情况下,jQuery 使用Content-Type: x-www-form-urlencoded
和熟悉的foo=bar&baz=moe
序列化传输数据。然而,AngularJS 使用 Content-Type: application/json
和 { "foo": "bar", "baz": "moe"}
JSON 序列化来传输数据,这不幸的是,某些 Web 服务器语言(尤其是 PHP)无法原生反序列化。
为了解决这个问题,AngularJS 开发人员提供了到 $http
服务的钩子(Hook),让我们可以实现 x-www-form-urlencoded
。
$http({
method :'POST',
url:'...',
data: data, // pass in data as strings
headers :{'Content-Type':'application/x-www-form-urlencoded'} // set the headers so angular passing info as form data (not request payload)
});
请阅读这篇文章以获得可行的解决方案:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
关于angularjs - Angular $http.post 返回空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051730/