0

I want to use node.js & express as a static server. I want it to serve all views without having to explicitly define routes. How do I do this?

4
  • 2
    Sounds like you would be better of with something like nginx, but just add the standard express static route and use files for everything, and it's all static ? Commented Jan 10, 2014 at 15:16
  • Its not all static, but I do not want to hardcode all my static routes. Commented Jan 10, 2014 at 15:37
  • Why on earth would you have to hardcode anything? Just add app.use(express.static(__dirname)); and the middleware takes care of all URL's that match a static resource. Commented Jan 10, 2014 at 15:40
  • Cool. I am a noob and didn't know that's how that worked. I'll just place the static html files into the public folder. If you write this as an answer I will vote on it. Commented Jan 10, 2014 at 16:55

2 Answers 2

1

To serve static files you can use the middleware provided by Express, just add

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

after your dynamic routes.

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

Comments

0

You should not use node.js as a static file server, use nginx instead. But if you have to or you are just playing with node, you can use this (coffeescript):

Handle static files:

app.use '/public/', express.static(__dirname + '/public')

Example:

<img src="/public/logo.jpg" alt="" />

Handle single app page:

app.get '/', (req, res)->
   res.sendfile './public/index.html'

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.