Serving Static Files in Express
moe-dizzle opened this issue · 3 comments
In Express, one can use app.use
and express.static
to bind the absolute directory path such as user/home/nodeproject/public to a shortcut: /public, so that html can locate files using a relative path.
For an example expressApp.use('/public', require('express').static(process.cwd() + '/public'));
With this I should be able to to display an image using a reative path in my html file, <img src="/public/img/goat.jpg" alt="chilling with a goat">
. In the docs, can you show where app.use
and express.static
should be used ? I tried the init method on the config/web.js file, but it doesn't work.
@Maurice-Hayward hey :) normally the init should work... I need to test that. But we handle this case in the routes.js
file, for static assets you can add a route like this:
{
method: 'GET',
path: '/node_modules',
handler: {
directory: {
path: 'node_modules'
}
}
},
@tjwebb maybe we should align with trailpack-hapi, I don't know the status but I think now you manage it in other way.
@jaumard Thanks you were right but both hapi and express are slightly different.
To get hapi to work I had to do this:
` {method: 'GET',
path: '/public/{param*}',
handler: {
directory: {
path: path.resolve(__dirname, '..', 'public'),
index:true,
listing: true,
redirectToSlash:true
}
}
}`
To get Express to work I had to do this:
`{
method: 'GET',
path: '/public/',
handler: {
directory: {
path: path.resolve(__dirname, '..', 'public'),
index:true,
listing: true,
redirectToSlash:true
}
}
}`