Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print to html with express node.js

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

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.

This is how the webpage is called

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

This is where the Node.js files are called:

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

And here is where the variable is:

T.get('search/tweets', { q: hash1 + ' since:2013-11-11', count: 5 },
    function(err, reply) {
        response = (reply),
        console.log(response)
        app.append(response)
    })
like image 516
user2954467 Avatar asked Oct 20 '22 19:10

user2954467


1 Answers

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

});

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

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>
like image 63
Hector Correa Avatar answered Oct 27 '22 10:10

Hector Correa