Search code examples
node.jsangularexpressangular4-httpclient

(Angular4 / MEAN) Sending Request to Local API Results in Empty Body


I'm trying to post data to an Items API, for instance:

"data": {
        "title": "stack",
        "notes": "asdsad",
        "time": "19:02",
        "meridian": "PM",
        "type": "Education",
        "_id": "5a2f02d3bba3640337bc92c9",
        "days": {
            "Monday": true,
            "Tuesday": false,
            "Wednesday": false,
            "Thursday": false,
            "Friday": false,
            "Saturday": false,
            "Sunday": false
        }
    }

However, when using HttpClient to post the data

  this.http.post("http://localhost:3000/api/items",
      JSON.stringify(item))
      .subscribe(
        (val) => {
          console.log("POST call successful value returned in body",
            val);
        },
        response => {
          console.log("POST call in error", response);
        },
        () => {
          console.log("The POST observable is now completed.");
        });

I always get the Bad Request 400 response from the Items Controller in the API.

exports.createItem = async function(req, res, next){

    // Req.Body contains the form submit values.
    console.log(req);
    console.log(req.body);
    var item = {
        id: req.body.id,
        title: req.body.title,
        days: req.body.days,
        notes: req.body.notes,
        time: req.body.time,
        meridian: req.body.meridian,
        type: req.body.type,
        completed: req.body.completed,
    }

    try{

        // Calling the Service function with the new object from the Request Body

        var createdItem = await ItemService.createItem(item)
        return res.status(201).json({status: 201, data: createdItem, message: "Succesfully Created Item"})
    } catch(e){
        console.log(e);
        //Return an Error Response Message with Code and the Error Message.
        return res.status(400).json({status: 400, message: "Item Creation was Unsuccesfull"})
    }
}

I have already set up BodyParser in my app.js as so

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

In the express console, the output is as follows

  _startTime: 2017-12-11T22:35:18.204Z,
  _remoteAddress: '::1',
  body: {},
  secret: undefined,
  cookies: {},
  signedCookies: {},
  route: 
   Route {
     path: '/',
     stack: [ [Object], [Object] ],
     methods: { post: true } } }
{}

As you can see the body is empty and this is preventing an item from being created. I have gone ahead and tested this using Postman and when sending url encoded form data and raw JSON data the posts are successful and return 200. However, I can never get the application's request to work.

Any help is appreciated as I have been struggling with this for several hours now.


Solution

  •   this.http.post("http://localhost:3000/api/items",
          JSON.stringify(item)    -----> convert JSON object to string
       ).subscribe(...);
    

    Based on your server side code, I believe that it expects JSON object other than a JSON string, therefore remove JSON.stringify(item)) from your client side, the body of your POST should be JSON object.