javascript - 如何从 Express 路线提供脚本文件

标签 javascript node.js api express

我有一个 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 the Content-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/

相关文章:

c# - 如果 API 速率限制超过使用 WebApiThrottle - C# Web API,则阻止 API 请求 5 分钟

javascript - 使用javascript模拟粘贴到Textarea

javascript - CoffeeScript 中的类

javascript - WebSocket 连接失败 : Error during WebSocket handshake: Unexpected response code: 400

javascript - 错误: defined function is not a function

ruby-on-rails-3 - 在 Rails Controller 中呈现和重新引发异常

javascript - Chrome 扩展 V3 无法读取未定义的 setBadgeBackgroundColor 的属性

javascript - 无法制作粘性导航栏

javascript - 如何将传递给 Nodejs 的查询字符串转发到通过 res.render 提供服务的页面?

c# - 如何使用 twitter api 获取 twitter 用户的电子邮件地址