Search code examples
node.jspostmannodemon

express.js server running on nodemon working differently than one on node


my server.js looks like this:

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

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

var ingredients = [
    {
        id:"i1",
        text:'eggs'
    },
    {
        id:'i2',
        text:'milk'
    },
    {
        id:'i3',
        text:'bacon'
    },
    {
        id:'i4',
        text:'frog legs'
    }
];
app.get('/',function (request,response){
    response.send(ingredients);
});
app.post('/',function(request,response){
    var ingredient = request.body;
    if( !ingredient || ingredient.text===""){
        response.status(500).send({error: "Your ingredient must have some text"});
    }else {
        ingredients.push(ingredient);
        response.status(200).send(ingredients);
    }
});
app.listen(3000, function () {
    /* body... */
    console.log('My first API running successfully on port 3000');
});

so when I run the server using node server.js and send a POST request with the body text as

{"id":"i5","text":"cherries"}

It pushes the object to the ingredients array. But when I run the same file using nodemon server.js , it pushes an empty object. Also, it doesn't return an error message if "text" property is left empty(also in the nodemon scenario). Can anyone from the community help me understand why did this happen ?

P.S. - I tested the requests using POSTMAN.


Solution

  • The reason you are pushing blank object in array is you are not passing application/json on header .

    And also your condition of checking text is not right.

     var ingredient = request.body;
        if( !ingredient || ingredient.text===""){
    

    //when you assign request.body to ingredient if no data come it assign {} to it and when you check for if condition !ingredient is not blank it has {} and in next condition ingredient.text return undefined which is not equal to ""

    app.post('/',function(request,response){
        console.log("post");
        var ingredient = request.body;
        if (!('text' in ingredient)){
       // if(ingredient.text){
            response.status(500).send({error: "Your ingredient must have some text"});
        }else {
             console.log("post1",ingredient);
            ingredients.push(ingredient);
            response.status(200).send(ingredients);
        }
    });