angularjs - Angular $http.post 返回空错误

标签 angularjs node.js post

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

相关文章:

javascript - AngularJS : Asynchronously initialize filter

javascript - 如何制作 angularjs 表指令

javascript - 如何在 Knex.js 中正确设置 `updatedAt` 时间戳?

javascript - 涉及 post json 调用的同步函数调用,其中一个函数应该在另一个函数成功后成功

c++ - QT 5.1.1 - 在 Post 请求中设置 urlQuery 的问题

javascript - 在 AngularJS 中动态填充下拉列表

javascript - AngularJS 通过内联表达式过滤

javascript - meteor JS : Can not assign a variable

performance - Node 的 SDCH 压缩?

javascript - 无法在 fetch() POST 请求中包含文件