If I change "< h1 >" to any other HTML tag such as "< h2 > or < p >" it fails to render them. I have no idea what's wrong.
const express = require("express");
const https = require("https");
const app = express();
// home page
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function (req, res) {
const queryCity = "London";
// const queryCity = String(req.body.cityName);
const apiKey = "lorem";
const url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
queryCity +
"&appid=" +
apiKey +
"&units=metric";
https.get(url, function (response) {
response.on("data", function (data) {
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
const feel = weatherData.main.feels_like;
const weatherIcon = weatherData.weather[0].icon;
const iconUrl =
"https://openweathermap.org/img/wn/" + weatherIcon + "@2x.png";
res.write(
"<h1>Temperature in " + queryCity + " is " + temp + "deg Celsius.</h1>"
);
res.write("It feels like " + feel + "deg Celsius.");
res.write("<img src=" + iconUrl + ">");
res.send(); // there can only be one res.send()
});
});
});
// server port
app.listen(3000, function () {
console.log("Server live on port 3000");
});
this is what happens when I change h1 to h2 or p. Img tag fails too. What am I doing wrong here?
This code never fail:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/html');
res.send('<h1>I am html</h1>');
});
app.listen(process.env.PORT || 8080);
Try to test your html generation with this basic code to be sure that error is not a nodejs issue.
Another tips:
res.write
to res.send
like my exampleres.write
several times, just one time sending a string previously created with your html linesHad this error as well earlier. Was able to fix it by adding an html tag on the first res.write
.
Using your code, it would be like this;
res.write(
"<html><h1>Temperature in " + queryCity + " is " + temp + "deg Celsius.</h1></html>"
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.