【问题标题】:Running an html response without opening the browser在不打开浏览器的情况下运行 html 响应
【发布时间】:2018-01-14 22:52:59
【问题描述】:

我正在尝试使用 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 文件中并在浏览器中打开的情况下做到这一点?

【问题讨论】:

  • 您在获取和提供文件时遇到了什么问题?见stackoverflow.com/help/mcve
  • 你能提供一个例子来说明你得到了什么,你在哪里加载它以及你是如何改变它的?例如,您是在 Node.js 中加载 HTML 文件,然后将 JS 文件附加到其中吗?
  • 我加了一个例子

标签: javascript html node.js request


【解决方案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>

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 2016-07-13
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多