Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs Post request to server

How would i gather that info im sending from the client? in this case, the id?

How can I get the id?

I do use client sided request:

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

and when i check server sided for req.body console.log(Req.body) i do get:

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

req.body.id returns:

undefined

How can i get the id of 4?

EDIT1:

the main code is located at https://github.com/meanjs/mean

server sided code:

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


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

    });
like image 423
maria Avatar asked Aug 23 '16 17:08

maria


4 Answers

You need to assign that id property to an object like

item = { id : 4 }

Lets suppose you have a text-box and the user wants to save a new item by inserting its name in it and click on submit.

Lets also suppose you are using a MongoDB collection of items, which have only id field for simplicity.

Here's what you should do to get it going easy.

Make sure you are importing bodyParser

var bodyParser = require('body-parser');

HTML - saving a new item with custom 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 part - 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);
                }
              });
   };
}

Route Handling - 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);
        });
    });

};

Post into 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);
        });
    });
}

If you try console.log() on the different pieces of code where I passed the item, you can properly see an object with id property.

I hope I've been helpful.

like image 53
AndreaM16 Avatar answered Oct 06 '22 00:10

AndreaM16


Make sure that you enabled JSON body parser in your node.js application.

var bodyParser = require('body-parser');
....
app.use(bodyParser.json());
like image 37
edtech Avatar answered Oct 05 '22 23:10

edtech


you miss the single quote :

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

in your example :

 return $http.post('/api/kill', {'id':4}, {
      headers: {}
  })
like image 34
Nicolas Law-Dune Avatar answered Oct 05 '22 23:10

Nicolas Law-Dune


response you are getting is not in object form

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

it is a key value pair and key is a string

'{"id":4}'

In order to get the right value at your end your json response shoulb be like

{ { 'id':4 } }

and then it will work like

    console.log(req.body); // { {"id":4} }
    console.log(req.body.id); // 4
like image 43
soCalledDeveloper Avatar answered Oct 05 '22 22:10

soCalledDeveloper