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

时间:2015-02-10 11:53:20

标签: node.js express static-files

我试图在Express和Node.js中构建应用程序。我的服务器文件包含在app文件夹中,前端内容位于公共文件夹中。

我的文件结构如下:

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)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

express.static中间件基于serve-static,负责提供Express应用程序的静态资产。

工作原理:

  • 为&#34; public&#34;提供应用的静态内容应用程序目录中的目录

    // GET /style.css等

    app.use(express.static(__ dirname +&#39; / public&#39;));

  • 将中间件安装在&#34; / static&#34;仅在其请求路径以&#34; / static&#34;

    作为前缀时才提供静态内容

    // GET /static/style.css等。

    app.use(&#39; / static&#39;,express.static(__ dirname +&#39; / public&#39;));

  • 提供来自多个目录的静态文件,但优先考虑&#34; ./ public&#34;超过其他人

    app.use(express.static(__ dirname +&#39; / public&#39;));

    app.use(express.static(__ dirname +&#39; / files&#39;));

    app.use(express.static(__ dirname +&#39; / uploads&#39;));

相关问题