1

This is my app.js in express.

var indexRouter = require('./routes/index');
var questionRouter = require('./routes/question');

...

app.use('/question', questionRouter); //a path  with / goes to indexRouter


app.use('/', indexRouter); //a path  with / goes to indexRouter

routes/index.js is

var express = require('express');
var router = express.Router();
let index = require('../controllers/index');


router.get('/', index.index);

module.exports = router;

routes/question.js is

var express = require('express');
var router = express.Router();
let question = require('../controllers/question');

router.get('/', question.question);

module.exports = router;

controllers/index.js is

  exports.index = function (req, res, next) {
    ...
    console.log('index2 page');//THIS GETS PRINTED 
    ...
    return response;
}

controllers/question.js is

exports.question = function (req, res, next) {
    console.log('question page'); //THIS DOESNT GET PRINTED
    return response;
}

When I run the following, the request goes to index.

GET http://localhost:4000/question
Content-Type: application/json

When I run the following, I get 404

GET http://localhost:4000/question/question
Content-Type: application/json

Why am I not able to reach question?

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • why use next is it middlewares you are creating? If yes why you define `question.question` you can simply do this `const {question} = require('../controllers/question');` and what that response coming from it looks like you didn't define remove the response and use this `res.json({message: "this is question"})` – Narayan Maity Jul 28 '23 at 05:09
  • and also `router.get('/', question);` Check if its work and please comment – Narayan Maity Jul 28 '23 at 05:10
  • I have made a new express app with your posted code and it accesses the question page correctly. So, I can't reproduce the problem from the posted code alone. So, the problem seems to lie somewhere else. – Geshode Jul 28 '23 at 05:20
  • @Geshode He has more code inside but he doesn't want to show us and I also don't see any problem with rather proper formatting of the code. – Narayan Maity Jul 28 '23 at 06:38
  • thanks folks. Being very new to `react`, I didn't know the difference between `app.get` and `app.use`. Using only `app.get` solved the issue. This question helped - https://stackoverflow.com/questions/15601703/difference-between-app-use-and-app-get-in-express-js – Manu Chadha Jul 29 '23 at 11:29

0 Answers0