如何在Express JS中包含静态文件 [英] How to include static files in express js
问题描述
我正在使用带有节点js的express js框架,并在我的server.js文件中使用了
I am using the the express js framework with node js and in my server.js file , i have used
app.use('/api',router);
在我的ejs文件中,当我使用脚本标记
In my ejs file , when i use a script tag
<script src = main.js>
我收到错误消息无法获取 http:// localhost:3000 / api / main.js
如何在ejs中包含这些文件
I get an error "Cannot get http://localhost:3000/api/main.js" How can i include these files in the ejs
请帮助!
推荐答案
您可以使用express.static中间件
You can use express.static middleware
app.use('/public', express.static('directory/containing/your/files'));
express.static的参数是包含要创建的所有文件的目录路径静态(您提供的路径可以相对于启动节点进程的目录,或者是绝对路径),该目录应该在文件系统中可用。
然后,您可能需要诸如:< img src ='/ public / imagesA.jpg'>
'/ public'装载路径是可选的,但建议
The parameter of express.static is the path to the directory containing all your files that you wish to make static (the path that you provide can be relative to the directory where you launch your node process, or an absolute path), the directory should be available in your file system.
Then you can require your resources like: <img src='/public/imagesA.jpg'>
The '/public' mount path is optional, but recommended
这篇关于如何在Express JS中包含静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!