【问题标题】:Angularjs Post request to serverAngularjs将请求发布到服务器
【发布时间】:2016-08-23 17:38:47
【问题描述】:

我将如何收集我从客户端发送的信息?在这种情况下,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

    });

【问题讨论】:

  • 您的服务器似乎错误地发回了数据
  • 我不明白你的意思。会怎样?您是在问怎么做,还是不确定怎么可能?
  • @ExplosionPills 我在问如何解决它
  • 服务器正在发回属性为{"id":4} 的内容,该属性没有任何值。我将不得不查看服务器代码
  • 服务器代码在那里,我只是输出req.body的结果

标签: angularjs node.js mean-stack


【解决方案1】:

您需要将 id 属性分配给类似的对象

item = { id : 4 }

假设您有一个text-box,并且用户想要通过在其中插入其名称来保存一个新项目并单击提交。

我们还假设您正在使用 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 property 的对象。

希望我对您有所帮助。

【讨论】:

【解决方案2】:

你错过了单引号:

var obj = { 'id':4 };
console.log(obj.id); //display 4

在你的例子中:

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

【讨论】:

    【解决方案3】:

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

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

    它是一个键值对,key是一个字符串

    '{"id":4}'
    

    为了在您的最后获得正确的值,您的 json 响应应该是这样的

    { { 'id':4 } }
    

    然后它会像这样工作

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

    【讨论】:

      【解决方案4】:

      确保您在 node.js 应用程序中启用了 JSON 正文解析器。

      var bodyParser = require('body-parser');
      ....
      app.use(bodyParser.json());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-27
        • 1970-01-01
        • 2016-02-27
        • 2020-09-17
        • 1970-01-01
        • 1970-01-01
        • 2016-09-29
        • 1970-01-01
        相关资源
        最近更新 更多