简体   繁体   English

将JS脚本移至Node.js的快速投放HTML页面中的外部文件

[英]Moving JS scripts to an external file in Node.js' express served Html page

I use express that returns me some html page: 我使用express返回我一些html页面:

app.get('/', function(req, res){
    return res.sendFile(path.resolve(__dirname + '/views/index.html'));
});

That index.html contains a bunch of scripts in the tag <script></script> . index.html在标记<script></script>包含一堆脚本。

I would like to move it to an external file like this: 我想将其移动到这样的外部文件中:

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

However it doesn't work and returns the following errors: 但是,它不起作用,并返回以下错误:

GET http://.../indexScripts.js net::ERR_ABORTED GET http://.../indexScripts.js net :: ERR_ABORTED

GET http://.../indexScripts.js 404 (Not Found) GET http://.../indexScripts.js 404(未找到)

Would you have any clue on what I should do? 您对我该怎么做有什么线索?

A solution I found is exposing the script: 我发现的解决方案是公开脚本:

app.get('/scripts', function(req, res){
    return res.sendFile(path.resolve(__dirname + '/views/indexScripts.js'));
});

... then using it: ...然后使用它:

<script src="scripts"></script>

But it really seems not the correct way of handling this / prone to security breach... 但这似乎不是处理此漏洞/容易导致安全漏洞的正确方法...

Thank you 谢谢

By default Express won't serve static files (JavaScript, CSS and images). 默认情况下,Express不会提供静态文件(JavaScript,CSS和图像)。 You need to use the express.static middleware to explicitly tell Express which folders it should serve from the file system. 您需要使用express.static中间件来明确告诉Express它应从文件系统提供哪些文件夹。

Example: 例:

app.use('/', express.static(path.join(__dirname, 'views')))

Then you can get your script file by navigating to http://localhost:3000/indexScripts.js . 然后,您可以通过导航到http://localhost:3000/indexScripts.js来获取脚本文件。

You can read more about the static middleware here . 您可以在此处阅读有关static中间件的更多信息。

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

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