简体   繁体   English

如何使用 nodejs 中的 express 渲染带有侧 js 文件的 HTML 文件?

[英]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我有一个 index.html 文件,我想发送它,使用

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另外,我在这个目录中有一些 js 文件,我想在 HTML 中使用它们

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

So, how can I make these js files accessible in HTML?那么,如何使这些 js 文件在 HTML 中可访问?

You can use what @fedeteka suggested.您可以使用@fedeteka 的建议。

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

The example above basically makes any file in the js folder to be accessed by the /js path.上面的示例基本上使js文件夹中的任何文件都可以通过/js路径访问。 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.可以通过访问localhost:{yourport}/js/script.jslocalhost:{yourport}/js/another.js等来访问这些文件。

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.只要你在 js 文件夹中有一个名为index.js的文件。

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

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