如何将参数传递给node.js中的HTML文件?

时间:2022-08-28 18:59:02

I have a code like res.sendfile('./home.html',{user:req.user}) and I want to access the user parameter in the HTML file. I don't want to use a template engine. How do I do this?

我有一个像res.sendfile('./ home.html',{user:req.user})的代码,我想访问HTML文件中的user参数。我不想使用模板引擎。我该怎么做呢?

1 个解决方案

#1


3  

If you don't want to use a template engine, you manually need to read in the file, then push whatever value you want into a placeholder...

如果您不想使用模板引擎,则需要手动读取文件,然后将所需的任何值推送到占位符...

var fs = require('fs');
...
  fs.readFile('./home.html', {encoding:'utf8'}, function(err, file){
    if (err) return res.end('ERROR');
    file = file.replace('%USER%', req.user);
    res.end(file);
  });

What you are describing is precisely what templates are for... now, if you want these variables to be available in JS.. then you may want a client "var cfg = %%CLIENT_CONFIG%%;" somewhere at the top, and you can JSON.stringify your config, and do the same replace.

您所描述的正是模板的用途......现在,如果您希望这些变量在JS中可用,那么您可能需要一个客户端“var cfg = %% CLIENT_CONFIG %%;”在顶部的某个地方,您可以JSON.stringify您的配置,并做同样的替换。

If you want a lightweight templating engine you can use manually, you probably want to use lodash's template method.

如果你想要一个可以手动使用的轻量级模板引擎,你可能想要使用lodash的模板方法。

#1


3  

If you don't want to use a template engine, you manually need to read in the file, then push whatever value you want into a placeholder...

如果您不想使用模板引擎,则需要手动读取文件,然后将所需的任何值推送到占位符...

var fs = require('fs');
...
  fs.readFile('./home.html', {encoding:'utf8'}, function(err, file){
    if (err) return res.end('ERROR');
    file = file.replace('%USER%', req.user);
    res.end(file);
  });

What you are describing is precisely what templates are for... now, if you want these variables to be available in JS.. then you may want a client "var cfg = %%CLIENT_CONFIG%%;" somewhere at the top, and you can JSON.stringify your config, and do the same replace.

您所描述的正是模板的用途......现在,如果您希望这些变量在JS中可用,那么您可能需要一个客户端“var cfg = %% CLIENT_CONFIG %%;”在顶部的某个地方,您可以JSON.stringify您的配置,并做同样的替换。

If you want a lightweight templating engine you can use manually, you probably want to use lodash's template method.

如果你想要一个可以手动使用的轻量级模板引擎,你可能想要使用lodash的模板方法。