在ExpressJS中点击路由时,返回动态创建的.js文件 [英] Return dynamically created .js file when route is hit in ExpressJS

查看:65
本文介绍了在ExpressJS中点击路由时,返回动态创建的.js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个ExpressJS应用程序,我希望它在命中路由时返回动态创建的.js文件.html < script> 标签将使用此路由.有什么办法吗?

I am building an ExpressJS app and I want it to return a dynamically created .js file when the route is hit. This route will be used by an html <script> tag. Is there any way to do this?

推荐答案

您需要将其作为客户端上的文件,并不意味着它也必须作为服务器端上的文件.为所需的文件编写路由,然后从处理程序中返回动态创建的脚本.

You need it to be a file on the client side does not mean that it has to be a file on server side as well. Write a route for the file you want and return the dynamically created script from the handler.

router.get("/public/js/notafile.js", function(req, res) {
    // This doesn't have to be a one liner
    res.send("function(){console.log('yey')}");
});

您可以使用下划线模板等模板,也可以使用模板文件,并替换占位符以动态生成复杂函数.

You can use a template, like underscore template or otherwise a template file and replace the placeholders to generate complex functions dynamically.

如果要提供客户端希望在/public文件夹下的文件,则可能需要在静态绑定之前将其绑定.I. E.之前:

If you are serving a file that the client expects is under your /public folder you may want to bind this before your static binding. I. E. Before:

app.use(express.static(__dirname + '/public'));

这篇关于在ExpressJS中点击路由时,返回动态创建的.js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆