Home > Software engineering >  After using express static function, Css and image still won't load up
After using express static function, Css and image still won't load up

Time:03-25

My program can't pick up on where the images and the css are located. tried adding a '/' before the "public", pointing to specific locations to get the css and image and nothing seemed to work for me. Here's my code:

javascript:

const express = require("express");
const request = require("request");
const bodyParser = require("body-parser");
const https = require("https");

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

app.get("/", function(req, res) {
    res.sendFile(__dirname   "/signup.html")
})

app.listen("3000", () => console.log("NEWSLETTER is running on port 3000."));

HTML:

    <main >
        <form action="/" method="post">
            <img  src="./public/images/[email protected]" alt="" width="120" height="100">
            <h1 >Please sign in</h1>

            <input type="text"  placeholder="First Name">
            <input type="text"  placeholder="Last Name">
            <input type="email"  placeholder="Email">

            <button  type="submit">Sign in</button>
            <p >&copy; 2017 – 2021</p>
        </form>
    </main>
</body>

Project layout:

/public
    /images
        /[email protected]
    /styles
        /signup.css

CodePudding user response:

You need to remove the public from the filepath:

Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.

Documentation

app.use(express.static('public'))

Now, you can load the files that are in the public directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

You might also consult this post: Express js static relative parent directory

  • Related