简体   繁体   中英

Express.js Route orgainisation

When I set-up some Routes i normaly do it like this:

app.get('/x', function(req, res) {
res.sendFile(path.join(__dirname + '/public/.../index.html'));});

The Problem with this is if you have JS or CSS in the Route Folders you cant host them.

So often I just added

app.get('/public/.../js/index.js', function(req, res) {res.sendFile (__dirname + '/public/.../js/index.js');});
app.get('/public/.../css/style.css', function(req, res) {res.sendFile (__dirname + '/public/.../css/style.css');});

just below the Route to make the JS and CSS accessible.

I already host library with express static

app.use('/lib', express.static('lib'));

But that is not Possible for JS and CSS in the Route folders (/public/.../js)

  • Is There a better Way to organize my files that are in the route folders ?

You might use virtual path, keeping your current directory structure, adding following route you can refer all your static files with /static prefix from under ./public subdirectory:

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

Eg you would be able to refer http://your_server/static/public/.../js/index.js . Please be aware, that in such case all files under /public might be accessed via /static prefix, so you should not have server code or server configs there.

Ideally for clarity you should host and refer all your static files from one root folder with type subfolders (eg /static/js, /static/css):

app.use('/static', express.static('static'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM