0

example in Express I have a route that linked to my ejs middleware.
Code 1 :

app.all("/sample", function(req,res,next){
    ejs.renderFile("./sample.ejs", {req,res,next,require,module:require("module")} {}, function(e, dt){
        res.send(dt.toString());
    });
});

everything fine in the first code. and in sample.ejs (second code) I want to request to some text file in Internet and return to HTML (and should use HTTP module)
Code 2:

<%
    var http=require("http");
    var url=require("url");

    var opt = url.parse("http://website.com/thisfile.txt");
    /* it will return "Hello World!" btw */
    var dt = ""
    var hReq = http.request(opt, function(hRes){
        hRes.on("data", function(chunk){
            dt+=chunk.toString();
        });
    });
    hReq.end();
%>
<h2>Here is the data is <%= dt %></h2>

and while i try to my browser. it just give me
Code 3:

<h2>Here is the data is </h2>

where I want it gave me Code 4:

<h2>Here is the data is Hello World!</h2>

How could I get that?
I just want to use HTTP Module or Net Socket Module. and I just want to edit the Code 2. Code 1 is permanently like that.

Farhan M Sabran
  • 57
  • 1
  • 10

1 Answers1

0

While EJS can run full JavaScript, you generally want to leave as much as possible out of the template and put more of your logic in your main express request handler.

Since the rendering is done server side anyway, nothing will change other than making it easier to read and test.

You should consider moving the HTTP request made in your EJS template into your app.all('/sample') handler and then just inject the result into your template. In this case that would be the final string collected from the HTTP request. You'll then end up with something like this. (This is untested code).

Also, while it is not required at all, I'd suggest taking a look at something like the request, this makes HTTP requests much easier!

var request = require('request');

app.all("/sample", function(req,res,next){

  // Make the HTTP request
  request('http://www.website.com/file.txt', function(err, response, body) {

    // Render the ejs template
    ejs.renderFile("./sample.ejs", {file: body}, function(e, dt) {
      // Send the compiled HTML as the response
      res.send(dt.toString());
    });
  });
});
Elliot Blackburn
  • 3,759
  • 1
  • 23
  • 42
  • couldn't I request http in ejs? – Farhan M Sabran Jun 14 '18 at 15:28
  • No you can't, you cannot use `require` in EJS, you'd have to extract the functionality into a helper if you _really_ wanted to call it via EJS. To do that you'd need to do something like this, but I'd advise against it for HTTP requests - https://stackoverflow.com/questions/12794860/how-to-use-node-modules-like-momentjs-in-ejs-views#18500846 – Elliot Blackburn Jun 14 '18 at 16:20