How to properly include external css and js files in index.html served with express/nodejs?

末鹿安然 提交于 2020-01-03 04:45:09

问题


I am trying to wrap my html in a nodejs express app (latest version of express). I try using res.sendFile to send my "index.html" file. I am running into an issue where there are a lot of 404s when loading the page in a browser because it can't find any of my js or css files. My js files are in the bower_components directory, some are in "js" directory. My css files are in a "css" directory.

Path for one is:

/bower_components/jquery/dist/jquery.min.js

What is the best way to update in my server.js file and my index.html file so that it can find all the "css" and "js" files?


回答1:


You can use the directive express.static

var server = express();
server.use(express.static(path.join(__dirname, 'static')));

It will look for a static folder to serve your static files. Just put your css and js files in this folder and reference them in the <head> part of your templates (index.html in your case)




回答2:


If you have this two line of code in your app.js file:

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

Then you need to put your HTML files in view folder. I myself use ejs (templator) for render HTML files and more ,by adding this line of code to my app.js :

app.set('view engine', 'ejs');

Then by changing your extention of HTML fils to .ejs you can render them with this code :

res.render('file_name');

More info

For example if you have a css file in /public/css/style.css you have to link to it in your html with this address : ./css/style.css or something like this.



来源:https://stackoverflow.com/questions/26128606/how-to-properly-include-external-css-and-js-files-in-index-html-served-with-expr

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