8

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

    });
maria
  • 207
  • 5
  • 22
  • 56
  • It seems like your server is sending the data back incorrectly – Explosion Pills Aug 23 '16 at 17:40
  • I don't understand what you mean. How would what be? Are you asking how, or are you not sure how it's possible? – Explosion Pills Aug 23 '16 at 18:38
  • @ExplosionPills im asking how to fix it – maria Aug 23 '16 at 18:39
  • 1
    The server is sending back content with a property of `{"id":4}` that has no value. I would have to see the server code – Explosion Pills Aug 23 '16 at 18:40
  • The server code is there, I'm only outputting the result of req.body – maria Aug 23 '16 at 18:41
  • Have you tried JSON.stringify()-ing the properties you wish to send to the server? It looks like it is taking your object, converting it to a string and attempting to use that as the key. Maybe something like `return $http.post('/api/kill', JSON.stringify({id:4})...` – Dave V Aug 23 '16 at 18:49
  • what does this log? `$http.post( '/api/kill', { id:4 }, { headers:{}}).then( function( rsp ){ console.log( 'rsp', rsp )})` – jusopi Aug 23 '16 at 18:50
  • Are you using express? If yes then do you have body-parser installed? https://github.com/expressjs/body-parser – Dawid Winiarczyk Aug 27 '16 at 12:15
  • @DawidWiniarczyk yes. and yes. – maria Aug 27 '16 at 12:16
  • Can you check your browsers network tab and tell us the outgoing data. Is it the correct JSON-Object? Is the content-type application/json? – PerfectPixel Aug 27 '16 at 12:22
  • Would be easier to identify the problem if we saw some of the server side code too. – noppa Aug 27 '16 at 12:23
  • chat anyone? ( btw, editing the question now in a min) – maria Aug 27 '16 at 12:23
  • Posting primitive type is has this issue in WebApi(.Net REST), may be its the same here.could you try $http.post('/api/kill', '"4"'); Another way to pass a primitive type is to pass it as query string 'api/kill?id=4' - just my 2 cents;may be its whole different with node.js – Developer Aug 27 '16 at 12:30
  • @Developer if i did api/kill?id=4, how would i retrieve it? – maria Aug 27 '16 at 12:30
  • you gotta read it from query string – Developer Aug 27 '16 at 12:31
  • how do i do that with mean / express @Developer ? – maria Aug 27 '16 at 12:33
  • I might be saying something stupid here as my experience with node is very minimal. this might help - http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js``. – Developer Aug 27 '16 at 12:36

4 Answers4

4

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.

AndreaM16
  • 3,917
  • 4
  • 35
  • 74
2

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: {}
  })
Nicolas Law-Dune
  • 1,631
  • 2
  • 13
  • 30
2

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
2

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

var bodyParser = require('body-parser');
....
app.use(bodyParser.json());
edtech
  • 1,734
  • 20
  • 20