Home > Blockchain >  Why is my HTML not rendering CSS when sent through express?
Why is my HTML not rendering CSS when sent through express?

Time:11-27

I am a starter at REST APIs and I'm still beginning to comprehend it. I wanted to do it for a website.

So, I just used res.sendFile(), It worked but, The CSS is not being rendered nor does the JS.

Why? Any help is appreciated.

Code:

const app = require("express")()
const PORT = 8000

/**
 * 
 * @param {string} name 
 * @returns 
 * 
 */

function getHTML(name) {
    return process.cwd()   "/html"   `/${name}`   `/${name}.html`
}

/**
 * 
 * @param {string} name 
 * @returns 
 * 
 */


app.get("/password-generator", (req, res) => {
    res.sendFile(getHTML("password-generator"))
})

app.listen(PORT, () => {
    console.log("Website is on!")
})

A picture of my file structure:

File Structure

CodePudding user response:

You have to serve the css file as well, not only the html.

The easiest approach would be to use static:

Replace your app.get and getHTML functions with just this one line:

app.use(express.static(process.cwd()   "/html"));

And then you can access your html file with just http://localhost:8000/password-generator/password-generator.html


Alternate solution: If you want to keep the code you already have and still access it through http://localhost:8000/password-generator then you can just make a separate function to get the css:

app.get("/password-generator/style.css", (req, res) => {
    res.sendFile(process.cwd()   "/html/password-generator/style.css");
});

or something of the sort and then in your html make sure you link to src="/password-generator/style.css" instead of src="style.css"

CodePudding user response:

This is happening because css is not compatible with express.

  • Related