简体   繁体   中英

How can I render a HTML file with side js files using express in nodejs?

I have a index.html file, which i want to send, using

app.get('/', (req, res) => { res.sendFile(`${__dirname}/index.html`) });

Also, I have some js files in this directory, which I want to use in HTML by

<script src="./js/index.js"></script>

So, how can I make these js files accessible in HTML?

You can use what @fedeteka suggested.

app.use('/js', express.static('js'));

The example above basically makes any file in the js folder to be accessed by the /js path. For example, if you have your file tree set up like

Main Folder
-----js
----------script.js
----------another.js
----------asmanyasyouwant.js

These files can be accessed by going to localhost:{yourport}/js/script.js or localhost:{yourport}/js/another.js , etc.

If you set it up this way, you can have

<script src="/js/index.js"></script>

as long as you have a file called index.js in the js folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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