cnak2
cnak2

Reputation: 1841

Route in Express not being found

I'm fairly new to building APIs with Node, Express and Mongo.

I'm trying to modularize my Express Mongoose API, but for some reason my code is not seeing the exported route.

When I use PostMan to test I get a 404 error.

All my files are located in the same folder

I have my main app.js file:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');

mongoose.connect('mongodb://localhost/guestbook');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(cors());    

app.use('/api', require('./routes/api'));


    // changes it to use the optimized version for production
    app.use(express.static(path.join(__dirname, '/dist')));

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });


module.exports = app;

I have my api.js file, which I reference in my app.js:

//DEPENDENCIES
var express = require('express');
var router = express.Router();


//include the routes file
var guestbook = require('./guestbook');

router.route('/guestbook');



//RETURN ROUTER AS MODULE
module.exports = router;

And finally my route, which is my guestbook.js file:

//DEPENDENCIES
var express = require('express');
var router = express.Router();


//GUESTBOOK END POINTS
var Guestbook = require('../models/guestbook')

router.route('/guestbook')

.post(function(req, res) {

    var guestbook = new Guestbook();

    guestbook.firstname = req.body.firstname;
    guestbook.lastname = req.body.lastname;
    guestbook.email = req.body.email;
    guestbook.postedon = req.body.postedon;
    guestbook.comment = req.body.comment;
    guestbook.rate = req.body.rate;

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

        res.json({ message: 'Post created!' })

    });

})

.get(function(req, res) {
    Guestbook.find(function(err, guestbook) {
        if (err)
            res.send(err);

        res.json(guestbook);
    });

});


router.route('/guestbook/:id')

.get(function(req, res) {

    Guestbook.findById(req.params.id, function(err, guestbook) {
        if (err)
            res.send(err);

        res.json(guestbook);

    });

})

.put(function(req, res) {

    Guestbook.findById(req.params.id, function(err, guestbook) {

        if (err)
            res.send(err);

        //USING OBJECT.KEYS TO UPDATE ONLY PARAMS PASSED
        Object.keys(req.body).forEach(function(prop) {
            if (typeof req.body[prop] !== 'undefined') {
                guestbook[prop] = req.body[prop];
            }
        });

        guestbook.save(function(err) {

            if (err)
                res.send(err);

            res.json(guestbook);

        });

    });

})

.delete(function(req, res) {

    Guestbook.remove({ _id: req.params.id }, function(err, guestbook) {
        if (err)
            res.send(err);
        res.json({ message: 'Successfully deleted!' });
    });

});


//RETURN ROUTER AS MODULE
module.exports = router;

If I were to rename my guestbook.js file to api.js and reference that directly from my app.js, everything works fine, but I'm trying to use an api.js file in the middle, so I can better organize my code.

Any sage advice on how to fix this would be great!! Not sure what I'm missing that gives me the 404 error.

Upvotes: 0

Views: 1120

Answers (2)

jfriend00
jfriend00

Reputation: 707158

You have a couple issues:

  1. You're using /guestbook too many times in your route definitions.
  2. You haven't actually hooked the guestbook.js into your routes.

So, it appears you've created routes for:

/api/guestbook/guestbook/
/api/guestbook/guestbook/:id

You need to remove one of the intervening .route('/guestbook') you have.

That's why when you remove the code in api.js that is doing the extra .route('/guestbook'), then things start to work.


You have to decide where you want to define the /guestbook part of the path. If you want it defined in api.js, then you can just leave that as is and in guestbook.js, change this:

router.route('/guestbook')

to this:

router.route('/')

And, change this:

router.route('/guestbook/:id')

to this:

router.route('/:id')

And, then to hook guestbook.js into the routing chain, you can change this:

router.route('/guestbook');

to this:

// hook up guestbook router
router.use('/guestbook', guestbook);

Upvotes: 2

Paul
Paul

Reputation: 36319

In API.js you're requiring the guestbook but never using it and just exporting the bare router that has nothing assigned to any actual handlers.

Upvotes: 0

Related Questions