millarnui
millarnui

Reputation: 549

Can't handle routes using Express

I'm just starting out and I've got a barebones app here with a routes file ./routes/index.js.

When I browse to http://localhost:3000/index for example index.js is hit but none of the routes match and the program just goes straight through to "return router;". If I browse to http://localhost:3000/ I get the same again.

All the browser does is think about it for a bit and then give me a ERR_CONNECTION_RESET.

app.js

var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var flash = require('connect-flash');

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

var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(flash());

app.use(require('./routes/index'));

module.exports = app;

index.js

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

function authorize(req, res, next) {
    if (true) {
        next()
    } else {
        res.status(403).send('Forbidden')
    }
}

module.exports = function(){

    router.get('/index', function(req, res) {
        res.send('index');
    });

    router.get('/hello/:name', function(req, res) {
        res.send('hello ' + req.params.name + '!');
    });

    router.get('/', function(req, res) {
        res.send('root');
    });

    return router;
}

Upvotes: 1

Views: 153

Answers (2)

millarnui
millarnui

Reputation: 549

Got there in the end... I changed

module.exports = function(){

    router.get('/index', function(req, res) {
        res.send('index');
    });

    router.get('/hello/:name', function(req, res) {
        res.send('hello ' + req.params.name + '!');
    });

    router.get('/', function(req, res) {
        res.send('root');
    });

    return router;
}

to

router.get('/index', function(req, res) {
    res.send('index');
});

router.get('/hello/:name', function(req, res) {
    res.send('hello ' + req.params.name + '!');
});

router.get('/', function(req, res) {
    res.send('root');
});

module.exports = router;

Upvotes: 0

jfriend00
jfriend00

Reputation: 707996

app.js is missing a line to actually start the server. You need to add this:

app.listen(3000);

Upvotes: 1

Related Questions