Home > OS >  HTML content displayed as pure string instead of getting rendered as a website
HTML content displayed as pure string instead of getting rendered as a website

Time:08-03

Hello I am getting started with implementing APIs in my project to build a Weather reporting project.This is my .js script.

const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function (req, res) {
    res.sendFile(__dirname   "/index.html");
});

app.post("/", function (req, res) {
    var city = req.body.cityName;
    var url =
        "https://api.openweathermap.org/data/2.5/weather?appid=13c938e16426e3aa234d67fc162bf227&q="  
        city  
        "";
    https.get(url, function (response) {
        response.on("data", function (data) {
            const weatherData = JSON.parse(data);
            var temp = weatherData.main.temp;
            var weatherDescription = weatherData.weather[0].description;
            var iconUrl =
                "https://openweathermap.org/img/wn/"  
                weatherData.weather[0].icon  
                "@2x.png";

            res.write("<img src="   iconUrl   ">");
            res.write(
                "<h1>the weather in "   city   " is = "   weatherDescription   "</h1>"
            );

            res.write("<h1>the temprature in your area is "   temp   " </h1>");

            res.send();
          
        });
    });
});

app.listen(3000, function () {
    console.log("the server has started at port 3000");
});

Now I get the response of the post request as

<img src=https://openweathermap.org/img/wn/[email protected]><h1>the weather in Gorakhpur is = scattered clouds</h1><h1>the temperature in your area is 304.93 </h1>   //Gorakhpur is name of city (:

this is as a string but i want it yo render it like a website.

Instead, when I do respond in this order the html is rendered just fine.

            res.write(
            "<h1>the weather in "   city   " is = "   weatherDescription   "</h1>"
            );

            res.write("<h1>the temprature in your area is "   temp   " </h1>");

            res.write("<img src="   iconUrl   ">");
            res.send(); 

            //Here I changed the order of image tag 

can you explain the reason behind it??

CodePudding user response:

Issue with this line,

res.write("<img src="   iconUrl   ">");

image tag in html has qoutes around src link. You html passing the src without qoutes. you can use single and double qoutes here.

res.write('<img src="'   iconUrl   '">');
  • Related