【问题标题】:How to print to html with express node.js如何使用 express node.js 打印到 html
【发布时间】:2013-12-23 02:58:25
【问题描述】:

如何在 html 中显示服务器端 node.js 的变量中保存的文本。

换句话说,为了更加清楚,我已经从访问 twitter (Twitt) 的 api 中提取了输出,并且我试图在页面底部显示该文本。

这就是网页的调用方式

app.get('/', function (req, res) {
    res.sendfile('./Homepage.html');
});

这是调用 Node.js 文件的地方:

var express = require('express');
var app = express();

这是变量所在的位置:

T.get('search/tweets', { q: hash1 + ' since:2013-11-11', count: 5 },
    function(err, reply) {
        response = (reply),
        console.log(response)
        app.append(response)
    })

【问题讨论】:

  • 我不明白你打电话给T 的确切位置。您将需要在您的快速路由中调用它,以便能够将其输出与您的响应一起发送。

标签: javascript html node.js express


【解决方案1】:

假设页面上注入的代码会随着每个请求而改变,你应该或多或少地拥有如下代码:

app.get('/', function (req, res){

  // make the call to twitter before sending the response
  var options = { q: hash1 + ' since:2013-11-11', count: 5 };
  T.get('search/tweets', options, function(err, reply) {
    // use RENDER instead of SENDFILE
    res.render('./Homepage.html', {data: reply});
  });

});

注意 (1) 我如何在请求中调用 Twitter,(2) 我正在使用 res.render() (http://expressjs.com/api.html#res.render) 而不是 res.sendFile()。

这样,您的视图 (homepage.html) 可以注入传递给 res.render() 的数据。根据您使用的模板引擎,语法可能会有所不同,但如果您使用的是EJS,则以下内容应该可以工作:

<p>your html goes here</p>
<p>The data from Twitter was <h2><%= data %></h2></p>
<p>xxx</p>

【讨论】:

    【解决方案2】:

    你需要使用类似 ejs 模板的东西。

    例如,在 app.js 中,您将拥有:

    app.get('/', function(req, res) {
      res.render('index', {base: req.protocol + "://" + req.headers.host});
    });
    

    然后在 index.ejs 中你将拥有

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Websitename</title>
      <base href="<%- base %>">
    </head>
    

    确保将您的视图引擎设置为靠近 app.js 的顶部

    app.set('view engine', 'ejs');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      相关资源
      最近更新 更多