使用快速静态函数后,Css 和图像仍然无法加载

After using express static function, Css and image still won't load up

我的程序无法获取图像和 css 所在的位置。尝试在“public”之前添加“/”,指向特定位置以获取 css 和图像,但似乎对我没有任何作用。这是我的代码:

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 class="form-signin">
        <form action="/" method="post">
            <img class="mb-4" src="./public/images/roundups-v0@2x.png" alt="" width="120" height="100">
            <h1 class="h3 mb-3 fw-normal">Please sign in</h1>

            <input type="text" class="form-control top" placeholder="First Name">
            <input type="text" class="form-control middle" placeholder="Last Name">
            <input type="email" class="form-control bottom" placeholder="Email">

            <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
            <p class="mt-5 mb-3 text-muted">&copy; 2017 – 2021</p>
        </form>
    </main>
</body>

项目布局:

/public
    /images
        /roundups-v0@2x.png
    /styles
        /signup.css

您需要从文件路径中删除 public

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'))

现在,您可以加载 public 目录中的文件:

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

你也可以参考这个post:Express js static relative parent directory