使用Express将JavaScript代码注入html [英] Inject javascript code into html with Express

查看:47
本文介绍了使用Express将JavaScript代码注入html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Express 框架编写一个Web应用程序,以生成 Impress.js 演示文稿并将可视化编辑器应用于这些演示文稿.我已经将 app.js 设置为仅获取.html文件,但是我想在.html文件的正文结束标记之前注入来自单独文件的javascript代码.

I am writing a web application using Express framework to generate Impress.js presentations and apply a visual editor on them. I have set up the app.js for only getting the .html file but I want to inject a javascript code from a separate file before the body closing tag of the .html file.

例如,我将有一个路由处理程序/edit ,然后在将脚本注入html代码后将触发该脚本.

For example, I will have a route handler /edit and then the script will be triggered after it have been injected into the html code.

var express = require('express');

var app = express();


app.configure(function(){
    app.use(express.static(__dirname + '/public'));
});

app.get('/:file', function(req, res) {
  res.sendfile(__dirname + '/public' + file);
});

app.listen(3000);
console.log('Listening on port 3000');

任何关于如何实现这一目标的想法都将受到欢迎!

Any ideas on how to achieve this would be more than welcome!

推荐答案

只是一个想法,但是您可以使用cheerio 将脚本附加到身体

Just an idea, but you could use something like cheerio to append a script to the body

app.get('/:file', function(req, res) {
  var html = fs.readFileSync(__dirname + '/public' + file, 'utf8');
  var $ = cheerio.load(html);
  var scriptNode = '<script>alert("script appended!");</script>';
  $('body').append(scriptNode);
  res.send($.html());
});

这篇关于使用Express将JavaScript代码注入html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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