sp312
sp312

Reputation: 49

Can't get users using restful API with node and mongodb

When I set up the route for users in server.js and test with postman/localhost I get the error message, cannot GET /users. Same with any other crud operation. How can I fix this route?

server.js

    var express     =   require("express");
    var app         =   express();
    var bodyParser  =   require("body-parser");
    var router      =   express.Router();
    var mongoOp     =   require("./models/mongo");

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

    router.get("/",function(req,res){
       res.json({"error" : false,"message" : "Hello World"});
    });

    router.route("/users")
        .get(function(req,res){
    var response = {};
    mongoOp.find({},function(err,data){
    // Mongo command to fetch all data from collection.
        if(err) {
            response = {"error" : true,"message" : "Error fetching data"};
        } else {
            response = {"error" : false,"message" : data};
        }
        res.json(response);
    });
});

    app.use('/',router);

    app.listen(3000);
    console.log("Listening to PORT 3000");

mongo.js

    var mongoose    =   require("mongoose");
    mongoose.connect('mongodb://localhost:27017/meanapi');

    var mongoSchema =   mongoose.Schema;

    var userSchema = {
        "userEmail" : String,
        "userPassword" : String
     };

     module.exports = mongoose.model('userLogin', userSchema);

Upvotes: 2

Views: 1526

Answers (1)

kio
kio

Reputation: 374

something helpful for these cases is to set NODE_ENV=development as an environment variable and use morgan. It prints out all the requests that hit your nodejs server with status code, method, path etc.

Here's a simple way to set it up:

if ('production' != app.get('env')) {
    app.use(morgan('dev'));
}

Another thing that helps in debugging is

app.on('error', function (err) {
    console.error(err); // or whatever logger you want to use
});

Ass that after all the middleware and it should print out if some requests fail to get all the way to your handlers.

Hope this helps!

Upvotes: 1

Related Questions