简体   繁体   English

如何从Express路由提供脚本文件

[英]How to serve script file from Express route

I have a js script that I want to include in src attribute in my html file. 我有一个js脚本,我想将其包含在html文件的src属性中。 When I am directly adding script from local path, it is working. 当我直接从本地路径添加脚本时,它正在工作。

Is it possible to return file path from an express route and use the route as value of src in my html? 是否可以从快速路由返回文件路径,并将该路由用作html中src的值? This is how I want to include my express route in html 这就是我要在html中包含我的快速路线的方式

<script src="http://localhost:2222/widget" type="text/javascript"></script>

Express server is running on port 2222 and has some apis. Express服务器在端口2222上运行,并具有一些API。 Now in my express route /widget 现在在我的快速路线/小工具中

app.get("/widget", (req, res) => {
     res.send(path.join(__dirname + "/src/client/public/bundle.js"));
});

When I simply trigger localhost:2222/widget a correct path shows up starting from /home/... 当我简单地触发localhost:2222 / widget时,从/ home /开始显示正确的路径。

I need some machanism to use this js file path as src (as shown above). 我需要一些机制来将此js文件路径用作src(如上所示)。

Note: I have added all cors, headers etc. for access control. 注意:我已经添加了所有cors,标头等用于访问控制。

Use res.sendFile() to send the file instead of the path: 使用res.sendFile()发送文件而不是路径:

Transfers the file at the given path . 在给定path传输文件。 Sets the Content-Type response HTTP header field based on the filename's extension. 根据文件名的扩展名设置Content-Type响应HTTP标头字段。 Unless the root option is set in the options object, path must be an absolute path to the file. 除非在options对象中设置了root选项,否则path必须是文件的绝对路径。

So, your code becomes: 因此,您的代码变为:

app.get("/widget", (req, res) => {
     res.sendFile(path.join(__dirname, "/src/client/public/bundle.js"), err => console.log(err));
});

Since you are using path.join() you can separate __dirname and the relative path by a comma. 由于您使用的是path.join() ,因此可以用逗号分隔__dirname和相对路径。

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

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