【问题标题】:Can someone please explain how static files in express js work?有人可以解释一下 express js 中的静态文件是如何工作的吗?
【发布时间】:2021-08-17 11:19:11
【问题描述】:

我是 nodejs 的新手,并且是 express 模块的新手。我有这样的应用设置;

chart.js 是我的 nodejs 文件。我正在尝试使用app.use(express.static(-I didn't understand what i need to write here-)) 使我的js 文件和css 文件静态化,以便正确呈现我的index.html,但我不知道如何使用并且我不了解文档。在文档中,他们说编码器能够使用像app.use(express.static('public')) 这样的静态,但他们没有提到什么是公共的,它在项目中的位置,它包含什么。有人可以帮我解决这种情况吗?这个 express.static 是如何工作的,我怎样才能使我的文件成为静态文件?

【问题讨论】:

标签: node.js express static-files


【解决方案1】:

注意:请勿将私人文件放入您的静态文件夹中。

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

您在express.static() 函数内部看到的是静态文件夹的路径,它将直接从浏览器访问,您无需编写其路由,因为该文件夹将向公众提供所有访问权限.比如css,js文件。以及您可以作为其目录访问的那些文件。

在上图中,您在位于应用程序根文件夹的 public 文件夹中有 html、css 和 js 文件。您需要访问那些与 nodejs 无关的公共静态文件,因此它应该在您的服务器节点 js 代码上定义为静态文件:app.use(express.static(__dirname + '/public'));。它会得到所有的路线,如:

http://localhost:3000/css/style.css
http://localhost:3000/javascript/script.js
http://localhost:3000/favicon.ico
http://localhost:3000/index.html
http://localhost:3000/robots.txt

您还可以为这些静态路由设置前缀。为此,您需要将前缀指定为:app.use('static_folder', express.static(__dirname + '/public'));,然后它将看起来像:

http://localhost:3000/static_folder/css/style.css
http://localhost:3000/static_folder/javascript/script.js
http://localhost:3000/static_folder/favicon.ico
http://localhost:3000/static_folder/index.html
http://localhost:3000/static_folder/robots.txt

【讨论】:

  • 非常感谢,我已经知道怎么用了。
猜你喜欢
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
相关资源
最近更新 更多