4

I've been having this issue where for some reason the Express route doesn't see my root get function. I've declared my app.js this way:

var index = require('./app/routes/index');
var app = express();
app.use('/', index);

Then in my index.js I have my definition this way:

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

router.get('/', function(req, res, next) {
  console.log('Enter root.');
});

router.get('/something', function(req, res, next) {
  console.log('Enter something.');
});

Express routes into '/something' just fine, but couldn't see '/'. Anybody have an idea why it doesn't work? Thanks.

franco
  • 667
  • 4
  • 7
  • 20

1 Answers1

2

Modified based on new info:

If you're getting a 304 status back in the browser, that's because the browser has cached the GET request and the server is telling the browser that the page has not been changed so the browser can just use the cached copy.

You can make the page uncacheable by changing the headers the server sends with the request.

See Cache Control for Dynamic Data Express.JS and NodeJS/express: Cache and 304 status code and Nodejs Express framework caching for more info.


You show no exports in index.js so this line:

var index = require('./app/routes/index');

does not accomplish anything. index is an empty object and thus this:

app.use('/', index);

doesn't do anything and, in fact, may even cause an error.


Perhaps what you want is this:

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

router.get('/', function(req, res, next) {
  console.log('Enter root.');
});

router.get('/something', function(req, res, next) {
  console.log('Enter something.');
});

// export your router
module.exports = router;

Then, index in your other file will be the router.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I do have my `module.exports = router` declared in the end. Sorry I forgot to add that line in the question. – franco Nov 28 '15 at 00:36
  • Then you probably just want `app.use(index);` so your router can see the top level URLs. – jfriend00 Nov 28 '15 at 00:38
  • I tried that and it still doesn't work. I tried to add a `router.post('/'...` to see if that works and it does. So my only problem really is the get method. Also it seems like my main page is getting a 304 status as opposed to 200. Is there anything to do with that? – franco Nov 28 '15 at 00:52
  • 1
    @franco - 304 status code means your page has been cached by the browser and Express is telling the browser that it has not been changed. If you don't want the page to be cached, you need to modify the headers from your server. FYI, the 304 status code is CRITICAL info on your question. – jfriend00 Nov 28 '15 at 00:55