将一个variables从node.js传递给html

我想从node.js传递一个variables到我的HTML文件。

app.get('/main', function(req, res) { var name = 'hello'; res.render(__dirname + "/views/layouts/main.html", {name:name}); }); 

我想通了,我能够通过这样的variables

 <script>var name = "<%= name %>";</script> console.log(name); 

你可以利用的是像帕格(以前的玉石)这样的模板引擎。 要启用它,您应该执行以下操作:

  1. npm install --save pug – 将其添加到项目和package.json文件中
  2. app.set('view engine', 'pug'); – 将其注册为快递视图引擎
  3. 创build一个./views文件夹并添加一个简单的.pug文件,如下所示:

html head title= title body h1= message注意间距是非常重要的!

  1. 创build一个返回处理过的html的路由:

app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); });

这将呈现一个index.html页面,其中在node.js中传递的variables已更改为您提供的值。 这已经直接从expressjs模板引擎页面中获取: http ://expressjs.com/en/guide/using-template-engines.html

有关帕格的更多信息,您还可以查看: https : //github.com/pugjs/pug

只有Node和HTML,你将无法实现你想要的; 它不像使用PHP,你可以做一些像<title> <?php echo $custom_title; ?> <title> <?php echo $custom_title; ?> ,没有任何其他的东西安装。

要使用Node来完成你想要的function,你可以使用一些叫做“模板”引擎的东西(比如Jade,检查一下),或者在Javascript中使用一些HTTP请求来从服务器获取数据,并用它来replace部分HTML与它。

两者都需要额外的工作; 它不像PHP那样可以像你想要的那样做任何事情。

我通过一个http API节点请求实现了这个function,它从客户端的HTML页面的节点对象返回所需的对象,

例如:API:localhost:3000 / username

从caching中按节点App对象返回已login的用户。

节点路由文件,app.get('/ username',function(req,res){res.json({udata:req.session.user});});

如果使用Express,则根本不需要使用View Engine,请使用如下所示的内容:

 <h1>{{ name }} </h1> 

如果您以前将您的应用程序设置为使用HTML而不是任何View Engine,则此方法可行

使用res.json,ajax,并承诺,与localStorage的一个很好的转折在任何地方使用它,添加令牌为罕见的街机爱。 PS,你可以使用cookies,但cookies可以咬https。

webpage.js

 function (idToken) { $.ajax({ url: '/main', headers: { Authorization: 'Bearer ' + idToken }, processData: false, }).done(function (data) { localStorage.setItem('name', data.name); //or whatever you want done. }).fail(function (jqXHR, textStatus) { var msg = 'Unable to fetch protected resource'; msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText; if (jqXHR.status === 401) { msg += '<br>Your token may be expired' } displayError(msg); }); 

server.js,使用express()

 app.get('/main', passport.authenticate('oauth2-jwt-bearer', { session: false }), function (req, res) { getUserInfo(req) //get your information to use it. .then(function (userinfo) { //return your promise res.json({ "name": userinfo.Name}); //you can declare/return more vars in this res.json. //res.cookie('name', name); //https trouble }) .error(function (e) {console.log("Error handler " + e)}) .catch(function (e) {console.log("Catch handler " + e)}); });