1

I am using Mongoose and nodejs to write an API.

My users.js looks as follow:

var express = require('express');
var router = express.Router();
var user = require('../models/users.js');


router.post('/',function(req, res, next) {
  console.log("made a post");

            var user2 = new user();     // create a new instance of the Bear model
            user2.firstName = req.body.firstName;  // set the bears name (comes from the request)
        user2.lastName=req.body.lastName;
        user2.email=req.body.email;

            user2.save(function(err) {
                if (err)
                    res.send(err);

            console.log("User created");
            });


        })

//The model acts as our user object...this returns all users.
    .get('/', function(req, res, next) {
      console.log("sending a get request");
        user.find(function(err, users) {
           if (err)
               res.send(err);

           res.json(users);
       });

      })

module.exports = router;

When I send a get request, it works perfectly. However, I am now trying to develop the POST request. I send a request such as the following:

http://localhost:4000/users?firstName=Han&lastName=Bo@email=haBo@yah.com

and I receive the following in my console:

    sending a get request
GET /users?firstName=Han&lastName=Bo@email=haBo@yah.com
 200 15.522 ms - 1365

And I receive the output of my GET request in the browser.

I'm new to node and would appreciate some help with this.

Thanks.

Matt Boyle
  • 385
  • 1
  • 6
  • 25

1 Answers1

2

You are putting your parameters as URL parameters, while your POST API reads parameters from body of request.

Here is explanation of POST parameters. Also, if you are not already using it, use postman to send requests.

Community
  • 1
  • 1
  • I was following a tutorial here: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 and his post request seems to work this way? – Matt Boyle Dec 30 '16 at 12:41
  • 1
    Take a look again, all of the post requests send their data as x-www-form-urlencoded in body of POST request, not as URL Params: https://cask.scotch.io/2014/04/node-api-postman-post-create-bear.png – Sulejman Sarajlija Dec 30 '16 at 12:55
  • This way of sending parameters is usually used in GET requests because there is no body in GET, only headers. – Sulejman Sarajlija Dec 30 '16 at 12:57