在expressjs中为带有响应对象的HTML文件提供服务时,如何包含外部JavaScript文件?

在expressjs中为带有响应对象的HTML文件提供服务时,如何包含外部JavaScript文件?,javascript,html,node.js,express,Javascript,Html,Node.js,Express,我的express应用程序在初次获取时(即,如果我在浏览器中点击“”)从我的磁盘提供一个HTML页面。现在我想访问一个JavaScript文件,它与HTML文件在磁盘中的位置相同。当我试图使用 <script src="/myJavaScriptFile.js" type="text/javascript" ></script> Express应用程序正在使用res.sendFile函数使用引用路径“\uu dirname”+”/index.html”为“index.

我的express应用程序在初次获取时(即,如果我在浏览器中点击“”)从我的磁盘提供一个HTML页面。现在我想访问一个JavaScript文件,它与HTML文件在磁盘中的位置相同。当我试图使用

 <script src="/myJavaScriptFile.js" type="text/javascript" ></script>
Express应用程序正在使用res.sendFile函数使用引用路径“\uu dirname”+”/index.html”为“index.html”提供服务。(我开始觉得这样做不好。如果你也这么认为,请告诉我)


正如我们在express应用程序中看到的,一个名为“test”的外部JavaScript文件与“index.html”和“express.js”位于同一位置,没有任何问题。有人能解释一下背景中到底发生了什么吗?如果我的'index.html'由express app提供服务,我可以在其中给出JavaScript文件的引用路径到底是什么?谢谢。

在Express-Express.static中的内置中间件的帮助下,提供图像、CSS、JavaScript和其他静态文件等文件

将要标记为静态资产位置的目录名传递给express.static中间件,以直接开始为文件提供服务。例如,如果将图像、CSS和JavaScript文件保存在名为public的目录中,则可以执行以下操作:

app.use(express.static('public'));
现在,您将能够加载公共目录下的文件:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

乐于助人

 var express = require('express')
 var testMethod = require('./test')
 var app = express()
 app.use(bodyParser.urlencoded({ extended:false }));

 var server = app.listen(3000, function () {

 var host = server.address().address
 var port = server.address().port

 console.log('Example app listening at http://%s:%s', host, port)

 })

 app.get('/', function (req, res) {
 console.log('In /');
 res.sendFile(__dirname + '/index.html');
 })
app.use(express.static('public'));
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html