Passing a variable from node.js to html

后端 未结 9 1259
孤独总比滥情好
孤独总比滥情好 2020-11-27 18:12

I am trying to pass a variable from node.js to my HTML file.

app.get(\'/main\', function(req, res) {
  var name = \'hello\';
  res.render(__dirname + \"/view         


        
相关标签:
9条回答
  • 2020-11-27 18:43

    If using Express it's not necessary to use a View Engine at all, use something like this:

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

    This works if you previously set your application to use HTML instead of any View Engine

    0 讨论(0)
  • 2020-11-27 18:46

    To pass variables from node.js to html by using the res.render() method.

    Example:

    var bodyParser = require('body-parser');
    var express = require('express');
    var app = express();
    
    app.use(express.static(__dirname + '/'));
    app.use(bodyParser.urlencoded({extend:true}));
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    app.set('views', __dirname);
    
    app.get('/', function(req, res){
        res.render('index.html',{email:data.email,password:data.password});
    });
    
    0 讨论(0)
  • 2020-11-27 18:49

    I found the possible way to write.

    Server Side -

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

    Client side (main.html) -

    <h1><%= name %></h1>
    
    0 讨论(0)
提交回复
热议问题