1

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!

2
  • Can you show your full routes/index.js file? What are you exporting? Where does router come from? Etc. .. Commented Aug 3, 2014 at 15:31
  • var express = require('express'); var router = express.Router(); module.exports = router; there is not more in my index.js. Different routes get called, its just this one route. Commented Aug 3, 2014 at 15:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry for being unclear, I already did that. When I remove serving of static files the route is called.
well its bsaically the same as this: stackoverflow.com/questions/16088824/… .. guess I have to rename the index.html or remove it from being served..
As an alternative, you can put app.use(express.static...) after app.use('/', routes);
I tried that, but then my route handler intercept all static requests :/
1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.