如何使用Express Node.js打印到html [英] How to print to html with express node.js

查看:310
本文介绍了如何使用Express Node.js打印到html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以HTML格式显示服务器端node.js变量中保存的文本.

How does one display text held in a variable on the server side node.js in html.

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

In other words, just to be doubly clear, I have output pulled from an api that accesses twitter (Twitt) and I am trying to display that text at the bottom of the page.

这是网页的调用方式

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

在这里调用Node.js文件:

This is where the Node.js files are called:

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)
    })

推荐答案

假设要在每个请求上更改要插入页面的代码,则应按以下方式添加或多或少的代码:

Assuming the code to inject on the page will change on every request, you should have the code more or less as follows:

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().

Notice how (1) I am making the call to Twitter inside the request, (2) I am using res.render() (http://expressjs.com/api.html#res.render) rather than res.sendFile().

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

This way, your view (homepage.html) can inject the data passed to res.render(). Depending on the template engine that you are using the syntax might be different, but if you are using EJS the following should work:

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

这篇关于如何使用Express Node.js打印到html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆