Search code examples
node.jsexpressgetroutesmiddleware

Can't route my get methods in Expressjs App


I have used express app1 command in console to generate an express app.

In app.js file I see that:

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 routes = require('./routes/index'); // <- Line A1
var users = require('./routes/users');  // <- Line A2
var tt = require('./routes/test');  // <- Line B1

var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 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: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes); // <- Line A3
app.use('/users', users); // <- Line A4
app.use('/test', tt); // <- Line B2

If you look at Line A1, Line A2 and Line A3, Line A4 you will notice some of the incoming requests are being routed to those paths. I checked the directory structure and I can find ./routes/index.js and ./routes/users.js .

So I wanted to add my own. I started by:

  • Adding lines B1 and B2.
  • Duplicating the users.js and renamed it to test.js
  • I restarted the nodejs server (using npm start)

The problem I have is when I browse to http://localhost:3000/test I get a 404 not found, while http://localhost:3000/users works just fine.

What am I missing here?

I would appreciate it if you could help me out.

Please be as specific as possible. Note that this code content is generated using express-generator.

Thanks.


Solution

  • Ok.

    I found out my mistake. In the test.js file, I was using router.get('/test', ... while I should have left the first parameter this way router.get('/', ... .

    So basically I was creating a route for:

    http://localhost:3000/test/test

    .