简体   繁体   中英

Serving static files from Node.js

I'm trying to serve static files from Node.js the only problem I'm having, is if I keep going into sub paths, like so:

localhost:3000/foo/bar/baz/quux

Then I have to step up the same amount of times, like this:

../../../../public/javascripts/whatever.js

As you can see that gets really annoying, is there a way to make Express v3 just know so that I can just do /public/javascripts/whatever.js instead of having to step up? Thanks in advance

This is my current static middleware for Express`

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

If you reference your static files from the root (ie src='/some/path/to/file.js' ), the url should not matter.

Example Website using Static Routing

Directory Structure

/public
    /css/style.css
    /js/site.js
/vendor/thoughtbrain/js/awesome-town.js
/views/view.html
/app.js

view.html


<!DOCTYPE html>
<html>
  <head>
    <!-- These files are served statically from the '/public' directory... -->
    <link href="/css/style.css" rel="stylesheet" >
    <script src="/js/site.js"></script>
    <!-- ... while this is "mounted" in virtual '/public' -->
    <script src="/public/js/awesome-town.js"></script>
  </head>
<body><p>Express</p></body>
</html>

app.js

var express = require('express'),
    http = require('http'),
    path = require('path'),
    app = express();

// Remember: The order of the middleware matters!

// Everything in public will be accessible from '/'
app.use(express.static(path.join(__dirname, 'public')));

// Everything in 'vendor/thoughtbrain' will be "mounted" in '/public'
app.use('/public', express.static(path.join(__dirname, 'vendor/thoughtbrain')));

app.use(express.static(path.join(__dirname, 'views')));

app.all('*', function(req, res){
  res.sendfile('views/view.html')
});

http.createServer(app).listen(3000);

With this application running,

http://localhost:3000

and

http://localhost:3000/foo/bar/baz/quux

both serve view.html and all referenced assets resolve.

Express Framework has a section on the use of static middleware here .

With that static() configuration, Express is already at least capable of finding /public/javascripts/whatever.js .

Though, it does depend on whether your public folder is in the same directory as your script (due to the use of __dirname when specifying the path).

If it is, the URL prefix /public should map to the file-system prefix of ./public (with . being __dirname ) so that:

A URL of `/public/javascripts/whatever.js`
Maps to `./public/javascripts/whatever.js`

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