Search code examples
node.jsexpressexpress-generator

Why doesnot the index route changes not work?


I created a new app using the express generator without any view engine. I go to http://127.0.0.1:3000 which shows the standard express welcome view. Then I add some query params to url like http://127.0.0.1:3000/?test1=testing&test2=testing234 and try to access these in the indexRouter's index.js but cannot access the query params. I tried

req.query.test1

and all other variants nothing works. Then I commented the line

app.use('/', indexRouter);

but I still can access the welcome screen. Commenting the below line throws error which i think is how it works as it is serving a static file.

app.use(express.static(path.join(__dirname, 'public')));

Is there any way I can access the query params in the home url in index router? What am I missing here?

app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;

indexRouter

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

/* GET home page. */
router.get('/', function (req, res, next) {
    console.log(req, 'request');
    console.log(res, 'response');
  res.render('index', { title: 'Express' });
});

module.exports = router;

Solution

  • You can access the req params by commenting out

    // app.use(express.static(path.join(__dirname, 'public')));

    And, change the response method Instead of rendering the static file

    // res.render('index', { title: 'Express' }); res.send('something');