【问题标题】:Angular $http.post returnd empty errorAngular $http.post 返回空错误
【发布时间】:2015-08-17 22:16:10
【问题描述】:

我正在使用 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 标头,但我不知道该怎么做。

任何帮助将不胜感激

【问题讨论】:

  • 客户端不会像这样发送 CORS 头,服务器是发回 Access-Control-Allow-Origin: * 让浏览器知道请求被允许的那个。

标签: angularjs node.js post


【解决方案1】:

问题在于您如何将数据传输到服务器。这是因为 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 服务中提供了挂钩,让我们强加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/

【讨论】:

  • 太好了,感谢您解释并提供指向非常有用的帖子的链接
猜你喜欢
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 2016-08-31
  • 2017-03-08
相关资源
最近更新 更多