我正在使用有 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/