Hello I am getting started with implementing APIs in my project to build a Weather reporting project.This is my .js script.
JavaScript
x
44
44
1
const express = require("express");
2
const bodyParser = require("body-parser");
3
const https = require("https");
4
const app = express();
5
app.use(bodyParser.urlencoded({ extended: true }));
6
7
app.get("/", function (req, res) {
8
res.sendFile(__dirname + "/index.html");
9
});
10
11
app.post("/", function (req, res) {
12
var city = req.body.cityName;
13
var url =
14
"https://api.openweathermap.org/data/2.5/weather?appid=13c938e16426e3aa234d67fc162bf227&q=" +
15
city +
16
"";
17
https.get(url, function (response) {
18
response.on("data", function (data) {
19
const weatherData = JSON.parse(data);
20
var temp = weatherData.main.temp;
21
var weatherDescription = weatherData.weather[0].description;
22
var iconUrl =
23
"https://openweathermap.org/img/wn/" +
24
weatherData.weather[0].icon +
25
"@2x.png";
26
27
res.write("<img src=" + iconUrl + ">");
28
res.write(
29
"<h1>the weather in " + city + " is = " + weatherDescription + "</h1>"
30
);
31
32
res.write("<h1>the temprature in your area is " + temp + " </h1>");
33
34
res.send();
35
36
});
37
});
38
});
39
40
app.listen(3000, function () {
41
console.log("the server has started at port 3000");
42
});
43
44
Now I get the response of the post request as
JavaScript
1
2
1
<img src=https://openweathermap.org/img/wn/03n@2x.png><h1>the weather in Gorakhpur is = scattered clouds</h1><h1>the temperature in your area is 304.93 </h1> //Gorakhpur is name of city (:
2
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.
JavaScript
1
11
11
1
res.write(
2
"<h1>the weather in " + city + " is = " + weatherDescription + "</h1>"
3
);
4
5
res.write("<h1>the temprature in your area is " + temp + " </h1>");
6
7
res.write("<img src=" + iconUrl + ">");
8
res.send();
9
10
//Here I changed the order of image tag
11
can you explain the reason behind it??
Advertisement
Answer
Issue with this line,
JavaScript
1
2
1
res.write("<img src=" + iconUrl + ">");
2
image tag in html has qoutes around src link. You html passing the src without qoutes. you can use single and double qoutes here.
JavaScript
1
2
1
res.write('<img src="' + iconUrl + '">');
2