Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading