40

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

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/" + "index.html");
});
<link rel="stylesheet" href="style.css">

I used the above Node.js code to send a html file. To get the html file formatted I need to send another css file (style.css).

My question is: How can I send both of these two files (index.html and style.css) using sendFile() and integrate them together in the client side?

1 Answer 1

90

The browser should load style.css on its own, so you can serve that as a route:

app.get('/style.css', function(req, res) {
  res.sendFile(__dirname + "/" + "style.css");
});

However, this would get very cumbersome very quickly as you add more files. Express provides a built in way to serve static files:

https://expressjs.com/en/starter/static-files.html

const express = require("express");
const app = express();
app.use(express.static(__dirname));

Keep in mind that if index.html is in the same directory as your server code you will also serve the server code as static files which is undesirable.

Instead you should move index.html, your css, images, scripts, etc. to a subdirectory such as one named public and use:

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

If you do this, Express will serve index.html automatically and you can remove your app.get("/" as well.

Sign up to request clarification or add additional context in comments.

5 Comments

great! BTW, does browser load style.css because of the following code? <link rel="stylesheet" href="style.css">
Yes, it might be worth you looking into some HTML stuff for jumping straight into node stuff.
@Explosion Pills : What if you are trying to hit that using postman, it will just return you the html
@ShashankGaurav I'm confused by your question; what are you trying to do with Postman?
i removed everything added all my files to a folder, added app.use(express.static("folderName")); and boom worked in root / url. Thanks for this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.