如何将传递给 nodejs 的查询字符串转发到通过 res.render 提供的页面
How can I forward a querystring passed to nodejs to a page served via res.render?
在我的nodejs文件中,我正在渲染一个名为foo.html的页面。在 foo.html 内部,我使用 ajax 从查询字符串中提取变量并相应地加载适当的 xml 文档。问题是,如果我运行我的nodejs服务器,我们将它称为localhost,并将查询字符串附加到其中,然后服务器将使用查询字符串而不是foo.html中的ajax调用。
有没有办法将查询字符串直接转发到 foo.html?
从nodejs文件内部,服务器.js:
app.get('/', function (req, res) {
var query = req.query;
if (query) {
if (query.screen == "page1") {
res.render('foo.html');
}
}
});
我可以想到 2 种方法可以做到这一点
1st way -) you can change your rendering engine and pass the query string variables as local variables to the template and store those values as variables inside a <script></script> tag
2nd way -) keep the html but don't render the file load it and modify it to contain the same script tag with the variables,
在这两种情况下,一旦您的页面加载完毕,您的JS将能够访问变量
-------------HTML 文件
----------------<script>
var a=/*text-to-replace-for-A*/;
var b=/*text-to-replace-for-B*/;
</script>
--------------请求处理程序
----------- var fs=require('fs'); //this goes in the require section
//this goes inside your function
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
var finalHTML=data.replace(/'/'*text-to-replace-for-A'*'//g,variableA).replace(/'/'*text-to-replace-for-B'*'//g,variableB);
res.send(finalHTML)
});
类似的东西应该注意到我正在使用一个简单的 readfile 和发送,这不是最快的解决方案,而是使用 html 修改的最简单的解决方案。 您还可以使用流动态修改内存中的文件。 您可以在以下位置找到 ReadFile 函数参考: http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback
相关文章:
- 无法让 res.render(..) 正常工作
- ExpressJS res.render无法使用angularjs
- res.render中出错,未定义函数
- 在express应用程序中异步执行res.render
- Res.render() not rendering
- 在jade javascript部分访问express res.render的输入数据
- Express.js res.render() and res.redirect()
- 如何将传递给 nodejs 的查询字符串转发到通过 res.render 提供的页面
- 有没有办法动态使用 res.render 和 url 参数
- 为什么 Express 渲染的页面不是在 res.render 中指定的
- 测试Express.js res.render在承诺与Mocha&Sinon spy
- 如何让 Express 在使用 res.render 时自动设置内容类型
- 如何在公共JS文件中使用通过Express res.render发送的JSON
- 在res.render()之后,手写笔没有应用于我的玉文件
- 自动将参数传递给 res.render nodejs
- res.render()前端的本地位置
- 如何在Express中从res.render访问数据
- Node.js/Express.js-如何覆盖/拦截res.render函数
- 使用Javascript从客户端的res.render访问数据
- 如何创建在res.render(模板渲染)之前运行的Express中间件