如何将传递给 nodejs 的查询字符串转发到通过 res.render 提供的页面

How can I forward a querystring passed to nodejs to a page served via res.render?

本文关键字:res render 字符串 查询 nodejs 转发      更新时间:2023-09-26

在我的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