加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angularjs向服务器发送请求

发布时间:2020-12-17 07:25:35 所属栏目:安全 来源:网络整理
导读:我如何收集客户端发送的信息?在这种情况下,身份证? 我怎样才能获得身份证? 我使用客户端请求: return $http.post('/api/kill',{id:4},{ headers: {} }) 当我检查服务器支持req.body console.log(Req.body)我得到: { '{"id":4}': '' } req.body.id返回:
我如何收集客户端发送的信息?在这种情况下,身份证?

我怎样才能获得身份证?

我使用客户端请求:

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

当我检查服务器支持req.body console.log(Req.body)我得到:

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

req.body.id返回:

undefined

我怎样才能得到4的id?

EDIT1:

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

服务器端代码:

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


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

    });
您需要将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>

角度部分 – 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属性的对象.

我希望我一直很有帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读