0

I'm having some troubles trying to stablish a REST API with nodeJS and express. The following code defines two routes, "stores" and "user".

Surprisingly, the route to "/user" is working nice but when a request arrives to "/stores" the request body appears undefined. I've searched for a solution but nothing seems to work for me.

Both controllers have the same structure.

What am I doing wrong?

var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require('mongoose');


// Connection to DB
mongoose.connect('mongodb://localhost/appDB', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});


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

//Import models and controllers
var userModel=require("./models/user.js")(app,mongoose);
var storeModel=require("./models/store.js")(app,mongoose);
var usersController=require("./controllers/users.js");
var storesController=require("./controllers/stores.js");

//Router options
var router=express.Router();



router.route('/stores')
.get(storesController.getNearestStores);

router.route('/user')
.post(usersController.addUser);

app.use(router);


//Start server
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});

Thank you very much.

P.S.:First time with nodejs and express(and even mongo)

Stennie
  • 57,971
  • 14
  • 135
  • 165
Andoni Martín
  • 231
  • 1
  • 3
  • 10

2 Answers2

1

This is because there is no body on a GET request in the http standard. Only POST and PUT.

What you want to do instead is use a query string

get
/stores?location=mystore

this way on your callback you have access to req.query

req.query
{
    location: 'mystore'
}
Brian Noah
  • 2,844
  • 15
  • 27
0

HTTP GET with request body

This gave me the solution, get requests don't accept parameters under HTTP standard.

Community
  • 1
  • 1
Andoni Martín
  • 231
  • 1
  • 3
  • 10