简体   繁体   中英

How do I serve a static file using Node Express?

I was having trouble settings up a very basic static file sever using express with Node.js. I set up a simple server.js but cannot see any files when I load the URL localhost:9000 in my web browser.

All I see is a page saying: Cannot get /

var express = require('express');
var app = express();

app.use(function(req, res, next) {
  next();
});

app.use(express.static(__dirname));

app.listen(9000);

Simply you're exposing nothing. Do you have, for example, an index.html file? Try this:

app.get("/", function(req, res) {
    res.sendfile("index.html");
});

Did you go through the NodeSchool workshoppers? They have step-by-step examples that cover this and more.

Here is the workshop for Express .

Here is my solution for the 'static' question in the workshop.

var express = require('express')
var app = express()

app.use(express.static(process.argv[3]||path.join(__dirname, 'public')));
 app.use(require('stylus').middleware(__dirname + '/public'));

app.post('/form', function(req, res) {
   res.writeHead(200, { 'Content-Type': 'text/plain' })
   res.end()
})

app.listen(process.argv[2])

Express does not create a directory listing. Even thought it does not list the files in the directory, it does serve them up when hitting them in the web browser.

Point the browser to the actual file:

http://localhost:9000/public/test.html

Originally I found this confusing because I had expected the express server to list directories; when seeing "something"... a page that said "Cannot get /" I assumed that page would normally have a list of files.

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