我尝试使用node.js(请求包)获取html文件的服务器响应,向其添加脚本并使用脚本运行此文件。
node.js
:
const request= require ('request')
const fs = require ('fs')
request.get ('www.google.com', (err, data, body) => {
if (err) throw err
body+='<script src="script.js"></script>'
fs.writeFile ('h.html', body)
})
script.js
:
window.onLoad = () =>alert ('something')
如果不在html文件中保存响应并在浏览器中打开它,我怎么能这样做?
答案 0 :(得分:1)
您可以执行以下操作:
var templateHtml = "<!DOCTYPE html><html><head></head><body>Your HTML</body></html>";
app.get('/your_resource',function(req,res){
res.send(templateHtml);
});
当然,您需要在templateHtml
脚本中替换。
请查看此answer以获取有关如何使用HTML模板的详细信息。
例如,假设您的项目中包含express-es6-template-engine
。
<强>的NodeJS 强>
var express = require('express'),
es6Renderer = require('express-es6-template-engine'),
app = express();
app.engine('html', es6Renderer);
app.set('views', 'views');
app.set('view engine', 'html');
app.get('/', function (req, res) {
res.render('index', {locals: {title: 'Welcome!', script: '<script>//script.js</script>'}});
});
app.listen(3000);
<强> HTML 强>
<!DOCTYPE html>
<html>
<head>
${script}
</head>
<body>
<h1>${title}</h1>
</body>
</html>
希望有所帮助!