具有相对路径的本地文件未加载到 NodeJS Express 应用程序中

Local files with relative paths are not loading in NodeJS Express app

我正在尝试在 Express 和 Node.js 中构建应用程序。我的服务器文件包含在 app 文件夹中,前端文件包含在 public 文件夹中。

我的文件结构如下:

my_project
|- app
|     |-(server stuff)
|     |- ....
|- public
|     |- modules
|     |     |- core
|     |     |     |- index.html
|     |     |     |- style
|     |     |     |     |style.css
|     |     |     |     |sidebar.css
|     |     |     |- img
|     |     |     |     |- faceicon.png
|     |     |     |     |- main.png
|     |     |     |- js
|     |     |     |     |main.js
|     |     |     |     |sidebar.js
|     |     |- articles
|     |     |     |- ....

问题是 在我的 index.html 文件中,当我引用像

这样的文件时
<link href="style/style.css" rel="stylesheet">

或者我的style.css喜欢

background: url(../img/faceicon.jpg) no-repeat bottom center scroll;

屏幕上没有显示预期的结果,我收到类似

的控制台消息
GET http://localhost:3000/img/faceicon.png 500 (Internal Server Error)

我该如何解决这个问题?

express.static middleware is based on serve-static,负责为 Express 应用程序的静态资产提供服务。

工作原理:

  • 从应用程序目录中的 "public" 目录为应用程序提供静态内容

    // GET /style.css 等

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

  • 将中间件挂载到“/static”以仅在其请求路径以“/static”为前缀时提供静态内容

    // GET /static/style.css 等

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

  • 从多个目录提供静态文件,但优先于“./public”其他目录

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

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

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