AngularJS向服务器发送POST请求

8

我怎样才能获取客户端发送的信息?在这种情况下,如何获取id?

我该如何获得id?

我使用客户端请求:

    return $http.post('/api/kill', {id:4}, {
              headers: {}
            })

当我在服务器端检查req.body时,console.log(Req.body)会得到以下结果:

 { '{"id":4}': '' }

req.body.id 返回:

undefined

如何获取数字 4 的 ID?

编辑1:

主要代码位于https://github.com/meanjs/mean

服务器端代码:

app.post('/api/kill', function (req, res) {


        console.log(req.body); // { '{"id":4}': '' }
        console.log(req.body.id); // undefined

    });

我不明白你的意思。你是指什么?你是在问如何做,还是不确定它是否可能? - Explosion Pills
@ExplosionPills 我在问如何修复它。 - maria
1
服务器返回的内容带有一个属性{"id":4},但是没有值。我需要查看服务器代码。 - Explosion Pills
你尝试过使用JSON.stringify()将要发送到服务器的属性进行字符串化吗?看起来它正在将你的对象转换为字符串,并尝试将其用作键。也许可以像这样:return $http.post('/api/kill', JSON.stringify({id:4})... - Dave V
这个日志会输出什么? $http.post( '/api/kill', { id:4 }, { headers:{}}).then( function( rsp ){ console.log( 'rsp', rsp )}) - jusopi
显示剩余12条评论
4个回答

4
你需要将那个“id”属性分配给一个对象,例如:
item = { id : 4 }
假设你有一个文本框,用户想通过在其中插入项目名称并单击提交来保存一个新项目。
还假设你正在使用一个项目的MongoDB集合,为简单起见,只有“id”字段。
以下是使它变得容易的步骤:
确保你导入了“bodyParser”。
var bodyParser = require('body-parser');

HTML - 保存具有自定义ID的新项目

<div class="form-group">
  <label for="id">ID</label>
    <input type="text" class="form-control" id="id" ng-model="ItemController.formData.id">
</div>

<button type="submit" ng-click="ItemController.createItem()" >Submit</button>

Angular部分 - ItemController.js

'use strict';

angular
    .module('myApp')
    .controller('ItemController', ItemController);

function ItemController($http) {

  var vm = this;

  /** Creates a New Marker on submit **/
  vm.createItem = function() {

          // Grabs all of the text box fields
          var itemData = {
              id        : vm.formData.id
          };

          // Saves item data to the db
          $http.post('/api/kill', itemData)
              .success(function(response) {
                if(response.err){
                  console.log('Error: ' + response.err);
                } else {
                  console.log('Saved '+response);
                }
              });
   };
}

路由处理 - routes.js

var ItemFactory   = require('./factories/item.factory.js');

// Opens App Routes
module.exports = function(app) {

    /** Posting a new Item **/
    app.post('/api/kill', function(req, res) {
        ItemFactory.postItem(req).then( function (item) {
          return res.json(item);
        });
    });

};

将内容发布到MongoDB - item.factory.js

var Item  = require('../models/item-model');
exports.postItem = postItem;

function postItem(item) {
    return new Promise( function (resolve, reject) {  
        var newItem = new Item(item.body);
        newItem.save(function(err) {
            if (err){
                return reject({err : 'Error while saving item'});
            }
            // If no errors are found, it responds with a JSON of the new item
            return resolve(item.body);
        });
    });
}

如果您在我传递项目的不同代码片段上尝试console.log(),则可以正确地看到具有id属性的对象。希望我能够帮上忙。

1
很快就会接受答案。能和你聊天吗?我还有一些其他问题。 - maria
我们可以在哪里与@andreaM16聊天? - maria
http://chat.stackoverflow.com/rooms/121999/angularjs-post-request-to-server - AndreaM16
你在线吗,@andreaM16? - maria
http://stackoverflow.com/questions/39193041/return-resolve-error-in-node-function @andreaM16 - maria

2

你得到的响应不是对象形式

 { '{"id":4}': '' }

这是一个键值对,其中键是一个字符串。

'{"id":4}'

为了在您的端获得正确的值,您的Json响应应该像这样:

为了获得正确的值,请确保您的Json响应格式正确。

{ { 'id':4 } }

然后它将像这样运作:
    console.log(req.body); // { {"id":4} }
    console.log(req.body.id); // 4

2
请确保在您的node.js应用程序中启用了JSON消息体解析器。
var bodyParser = require('body-parser');
....
app.use(bodyParser.json());

2
您忘记了单引号:
var obj = { 'id':4 };
console.log(obj.id); //display 4

在你的例子中:
 return $http.post('/api/kill', {'id':4}, {
      headers: {}
  })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接