user2071301
user2071301

Reputation: 77

express.js: Route Function not called express.js

My express.js configuration looks like this:

//app.js:
var routes = require('./routes/index');
app.use(express.static(path.join(__dirname, '../client/build'), {'index': false}));
app.use('/', routes);

//routes/index.js:
router.get('/', function(req, res) {
 console.log("im never called");
});

My handler is NEVER called (should be called when requesting without path or just '/'), the browser just gets a 303 with Location //, what is wrong here?

Thanks in advance for help!

Upvotes: 1

Views: 790

Answers (2)

JRulle
JRulle

Reputation: 7568

I was having this same issue this morning and I thought I would share my solution.

The express.static method is running on all of your requests... when it cannot find a match, it can either run the next() function and continue to your desired handler or redirect to a trailing slash to check if the request is for a directory.

I fixed it by adding 'redirect:false' as follows:

app.use(express.static(
    path.join(__dirname, '../client/build'), 
    {index: false, redirect: false}));


Reference: express.static(root, [options])

Upvotes: 1

Oleg
Oleg

Reputation: 23277

Try to add module.exports = router; to the end of routes/index.js

Edit:

There is a common practice to put all your static files in one directory (maybe you have done it already) and make all requests to static files start with /public:

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

Doing this way

http://yoursite.com/public/some/file.js

will be served with

../client/build/some/file.js

Instead of /public you may choose a path that will not intersect with your router.

Upvotes: 1

Related Questions