我有一个 js 脚本,我想将其包含在 html 文件的 src 属性中。当我直接从本地路径添加脚本时,它正在工作。
是否可以从快速路由返回文件路径并在我的 html 中使用该路由作为 src 的值?这就是我想在 html 中包含我的快速路线的方式
<script src="http://localhost:2222/widget" type="text/javascript"></script>
Express 服务器在端口 2222 上运行并具有一些 api。现在在我的快速路线/widget
app.get("/widget", (req, res) => {
res.send(path.join(__dirname + "/src/client/public/bundle.js"));
});
当我简单地触发 localhost:2222/widget 时,会显示从/home/... 开始的正确路径
我需要一些机制来使用这个js文件路径作为src(如上所示)。
注意:我已经添加了所有 cors、 header 等以进行访问控制。
最佳答案
使用res.sendFile()
发送文件而不是路径:
Transfers the file at the given
path
. Sets theContent-Type
response HTTP header field based on the filename’s extension. Unless the root option is set in the options object,path
must be an absolute path to the file.
所以,你的代码变成:
app.get("/widget", (req, res) => {
res.sendFile(path.join(__dirname, "/src/client/public/bundle.js"), err => console.log(err));
});
由于您使用的是 path.join()
,因此您可以用逗号分隔 __dirname
和相对路径。
关于javascript - 如何从 Express 路线提供脚本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50331113/