'the res.write in express displays the HTML element inside of it

I am not to web app dev and I started using express and I have this code

app.post("/", function(req, res) {

  var crypto = req.body.crypto;
  var fiat = req.body.fiat;
  var amount = req.body.amount;

  var options = {
    url: "https://apiv2.bitcoinaverage.com/convert/global",
    method: "GET",
    qs: {
      from: crypto,
      to: fiat,
      amount: amount
    }
  };
  request(options, function(error, response, body) {
    var data = JSON.parse(body);
    var time = data.time;
    var price = data.price;
    res.write("Current time is: " + time);
    res.write("<p> Your " + amount + " " + crypto + " is worth " + price + 
    " " + fiat + "</p>");
    res.send();
  });
});

But when I run my server and and run the POST request what is displayed on the page looks like this:

Current time is: 2019-06-29 18:50:35 <p> Your 2 BTC is worth 23954.24 USD</p>

From what I know res.write() isn't supposed to render the HTML and not show the HTML elements as text.

Am I doing something wrong here?? How can I fix it so the HTML tags don't show up in the page as text?

Thank you in advance :)



Solution 1:[1]

Try any of the below codes before this line:

res.write("Current time is: " + time);

  • res.writeHead(200, {'Content-Type': 'text/html'})
  • res.header('Content-Type', 'text/html')
  • res.type('text/html')

After this, try clearing cache too if it doesn't help.

That's actually just vanilla nodejs. Read more here: https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers

Solution 2:[2]

res.write("<html><p> Your " + amount + " " + crypto + " is worth " + price + 
" " + fiat + "</p></html>");

this should fix it. adding html tags around the paragraph tags should work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ibrahim khan