简体   繁体   中英

Cannot get app.css, main.js, other files to load using an Express server

I have the following code:

var express = require('express');
var app = express();
var server = require('http').Server(app);

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

server.listen(3000);

However, only my index.html page displays, and I have a GET error for my other files. When I load index.html at localhost:3000, I have errors in the console with trying to find my main.js and app.css files. Even when I include my other files as a src in the html file, they are not able to load. I think this may be because I am only sending the single html file to the server. How can I handle this so that all of the relevant files are sent to the server?

Using

res.sendfile(__dirname + '/index.html');

in response to a get request won't serve up all your static files, only the individual index.html file — meaning your css and javascript files will not be found by your server (even when you link to them in your html).

You need to use the included express static middleware (the only included middleware in express v4).

If your static files are in the same directory as your server.js file then add

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

This serves up all of your local static files and makes them accessible on your server.

I wrote a blog post on this a while back:

https://medium.com/@willsentance/how-to-avoid-main-js-style-css-not-found-or-how-i-learned-to-love-serving-static-files-with-node-2121255da0fd

You haven't offered a route to the linked files.

Use the static middle-ware: http://expressjs.com/api.html#express.static

From the docs:

Following are some examples of using the express.static middleware in an Express app.

Serve static content for the app from the "public" directory in the application directory.

// GET /style.css etc
app.use(express.static(__dirname + '/public'));

Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".

// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));

Disable logging for static content requests by loading the logger middleware after the static middleware.

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

Serve static files from multiple directories, but give precedence to "./public" over the others.

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));

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