Patrick Fenster
Patrick Fenster

Reputation: 1

How can I serve external css/js files to html files displayed by a NodeJS app?

I would like to serve html files at given URLs using only NodeJS, or a very lightweight and flexible other way. I've been able to serve those html pages using Express but there are things I don't like (the fact we must use a public folder and all the dependencies), and the external css/js just don't load.

I use something in the server.js file like :

app.get('/', function() { app.sendFile('index.html')});

And in the index.html file :

<link rel="stylesheet" href="style.css">

All the files are in the same folder.

Upvotes: 0

Views: 509

Answers (1)

Andrei Karpuszonak
Andrei Karpuszonak

Reputation: 9034

In express you could you static middleware.

In the example below you define public directory to store it.

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

Now you can put your style.css to this folder and it will be served as a static content.

More about middleware: http://expressjs.com/en/guide/using-middleware.html

Upvotes: 1

Related Questions