gpt4 book ai didi

express - Express 中虚拟路径前缀的用途

转载 作者:行者123 更新时间:2023-12-02 03:03:27 29 4
gpt4 key购买 nike

在服务器端提供静态服务的方式在 Express 中似乎非常简单:

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files directly. For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:


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

Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL.



要使用多个静态 Assets 目录,请调用 express.static
中间件功能多次:
app.use(express.static('public'))
app.use(express.static('files'))

Express 按照您使用 express.static 中间件函数设置静态目录的顺序查找文件。

我得到了虚拟路径前缀的想法,但你为什么要使用它呢?

To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:


app.use('/static', express.static('public'))

现在,您可以从/static 路径前缀加载公共(public)目录中的文件。
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

最佳答案

我知道这有点晚了,但希望这可以帮助你。顺便说一句,我不相信答案,只是深入了解您的担忧并发现了这一点。

This technique comes in handy when providing multiple directories to serve static files. The prefixes are used to help distinguish between the multiple directories.



如果你想深入挖掘。我在这个链接上找到了它:
https://guide.freecodecamp.org/nodejs/express/

关于express - Express 中虚拟路径前缀的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44393233/

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