gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:48:09 24 4
gpt4 key购买 nike

我正在尝试使用 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中间件基于 serve-static ,并负责为 Express 应用程序的静态 Assets 提供服务。

工作原理:

  • 从应用程序目录中的“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'));

关于node.js - 具有相对路径的本地文件未加载到 NodeJS Express 应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28431003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com