How to send multiple lines of HTML in res.send – Javascript

We can send multiple lines of HTML through the res.send the response in node js. This can be done by using the res.write()

Eg:

res.write("<p> The Weather is currently "+ description +"</p>")

res.write("<h1>The temperature is "+temp + " degree Celcius </h1>")

res.send();

Here is an example code of a weather app project part. Where the weather data is taken using an API and the details are printed.

Source code:

const express = require("express");
const https = require('https');
const app = express();

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

    const url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=d6b5462917dd2991ef81dbb470eb5564&units=imperial";

    https.get(url, function(response) {
        console.log(response.statusCode);

        response.on("data", function(data) {
            const weatherData = JSON.parse(data)
            const temp = weatherData.main.temp;
            const description = weatherData.weather[0].description;

            res.write("<p> The Weather is currently " + description + "</p>")
            res.write("<h1>The temperature is " + temp + " degree Celcius </h1>")
            res.send();

        })
    })

})

app.listen(3000, function() {
    console.log("Server is running on port 3000");
})

Output:

About the Author: smartcoder

You might like

Leave a Reply

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