简体   繁体   English

有没有办法避免在 express 中对每个 static 文件使用 app.get() ?

[英]Is there a way to avoid using app.get() for every static file in express?

I'm starting out with express.js and trying to serve lots of static files from the server (could be .css , .jpg , .svg , .js or other file types).我从express.js开始,并尝试从服务器提供大量 static 文件(可能是.css.jpg.svg.js或其他文件类型)。 Is there a way to do this without typing app.get() for each file?有没有办法在不为每个文件键入app.get()的情况下执行此操作? I know about express.Router() but then the clutter just goes over into another file.我知道express.Router()但随后混乱就进入了另一个文件。

You might want to use express.static middleware.你可能想使用express.static中间件。

For example, use the following code to serve all the files from directory named public:例如,使用以下代码为名为 public 的目录中的所有文件提供服务:

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

Now, you can load the files that are in the public directory:现在,您可以加载公共目录中的文件:

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

More info here: https://expressjs.com/en/starter/static-files.html更多信息在这里: https://expressjs.com/en/starter/static-files.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM