如何使用express node.js打印到html

How to print to html with express node.js

本文关键字:打印 html js node 何使用 express      更新时间:2024-04-03

如何在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)
    })

假设要在页面上注入的代码在每次请求时都会发生变化,那么您应该或多或少地拥有如下代码:

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()的数据

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

您需要使用类似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');