How to include static files in express js

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 01:43:53

问题


I am using the the express js framework with node js and in my server.js file , i have used

app.use('/api',router);

In my ejs file , when i use a script tag

<script src = main.js>

I get an error "Cannot get http://localhost:3000/api/main.js" How can i include these files in the ejs

please help!!!


回答1:


You can use express.static middleware

app.use('/public', express.static('directory/containing/your/files'));

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




回答2:


You serve static files through an included middleware in Express - express.static('folder/with/resources'). You do so by adding it to the middleware chain using app.use.

Let's say you want to serve your static files located in the local folder /dist through the public URL /static.

import express from 'express';
const app = express();

app.use('static', express.static('dist'));

Read more about it here.




回答3:


in app.js you have to add static folder directory access

app.use(express.static(path.join(__dirname, 'public')));

in public folder add your folders files

--public
----javascript
----css
----img

inside javascript add your main.js

and in ejs add

<script src = "javascript/main.js"></script>


来源:https://stackoverflow.com/questions/39912609/how-to-include-static-files-in-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!