[SOLVED] Typescript, pass arguments to Ejs page

Issue

I didn’t set anything like the code below at first, just res.render(‘view’, {prams}); I kept getting an error saying that the set header does not work.

"Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"

Then, now that it is covered with the header below code, the related error has disappeared, but the ejs page is not receiving any parameters and <%=%> does not work. I’m not good at node js, so I’m actually using it as a clone. Could this possibly have something to do with cors? (I don’t know what cors is well) Is there any way to send parameters here anyway?

            res.statusCode = 200;
            
            res.setHeader('Content-Type', 'text/plain');
            res.writeHead(200, {'Content-Type': 'application/xhtml+xml; charset=utf-8'});
            res.header({'Content-Type': 'application/xhtml+xml; charset=utf-8'});
            res.status(200).render("abcejs", {dataA, dataB});

Solution

You are not defining data properly. I am assuming your data is defined as follows:

var dataA = somedataA;
var dataB = somedataB;

And you are passing them like this:

res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.writeHead(200, {'Content-Type': 'application/xhtml+xml; charset=utf-8'});
res.header({'Content-Type': 'application/xhtml+xml; charset=utf-8'});
res.status(200).render("abcejs", {dataA, dataB});

You should display data in following manner:

<%= dataA %>
<%= dataB %>

You can’t print <%= data %> as you defined dataA and dataB. if you want to display parameters with different names then you have to define them while rendering like this:

 res.status(200).render("abcejs", {
  data1: dataA, 
  data2: dataB
 });

then you can display with <%= data1 %> <%= data2 %>

Learn more about ejs syntax: ejs.co

Answered By – Aimsat

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *