-1

My CSS is not applying when I host my html file using Express. Why is that happened and is there a way to add my CSS file using Express?

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({
  extended: true,
}));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.post('/', (req, res) => {
  console.log(req.body);
  res.send("You just posted");
});

app.listen(4400, () => {
  console.log("Server is running on port 4400");
});

enter image description here

I tried to add my CSS file using Express.

2
  • Where are you trying to apply your css exactly? Into your html? Commented Mar 11, 2023 at 22:11
  • Yes, I forgot put my html code. I add it with link tag. Commented Mar 11, 2023 at 22:18

1 Answer 1

0

The easiest way you can do this is by creating a folder named public and place inside it your html and css files. Then in your index.js you should put this line of code in order for your server to use this files

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

Then in your html file you will link the css file with the path

<link rel="stylesheet" type="text/css" href="style.css" />

For more information check some of the old posts:

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

Comments

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.