Max Max - 1 month ago 4
CSS Question

How do I use CSS and JS files within a HTML file being sent with Express?

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

app.get('/', function(req, res) {
res.sendFile('main.html', { root : __dirname})
});

app.listen(9000, function(){
console.log('Listening on port 9000');
});


This current block of code works fine. Express is required and assigned to the variable app.

A HTML file is then sent (from the same directory) using res.sendFile as part of the app.get method.

Within the HTML file I am referencing a css file in the same directory, yet nothing is happening.

<link rel='stylesheet' type='text/css' href='mainstyle.css'>


How am I able to send the CSS file to the browser for use? res.sendFile does not work.

Thanks.

Answer

You need to define a static files directory. Create a folder called public and then include this line:

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

Don't include public in the file path when you include the css file though. All of your static files can go in that folder. Or, better still, create sub-folders for styles, images, fonts etc.

You can read more about it here: https://expressjs.com/en/starter/static-files.html

I think the problem you're having is that you're trying to create a web application from scratch using Express without any of the surrounding functionality. Your app sends a file when you navigate to the URL. It does not listen for specific requests for files and respond to them, it does not handle missing files, server errors etc.

You could do all that from scratch but in fact Express have created an application generator which creates a skeleton app for you with the web server, public folder, routes etc. It's called Express Generator and you can find it here: https://expressjs.com/en/starter/generator.html

That's a brilliant starting point for an MVC application. You get the package.json file for additional node modules, a template engine called Jade (although I prefer Hogan) for dynamic content and once it's created your app, you can fire it up by typing "npm start" in a console window.

Comments