[英]Angular $http.post returnd empty error
我使用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標頭,但我不知道該怎么做。
任何幫助,將不勝感激
問題是如何將數據傳輸到服務器。 這是因為jQuery和Angular以不同方式序列化數據。
默認情況下,jQuery使用Content-Type: x-www-form-urlencoded
和熟悉的foo=bar&baz=moe
序列化來傳輸數據。 然而,AngularJS使用Content-Type: application/json
傳輸數據Content-Type: application/json
和{ "foo": "bar", "baz": "moe" }
JSON序列化,遺憾的是一些Web服務器語言 - 特別是PHP - 本身不會反序列化。
為了解決這個問題,AngularJS開發人員在$http
服務中提供了鈎子,讓我們強制使用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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.