res.write not working properly. It's showing output including HTML tags

大兔子大兔子 提交于 2021-02-04 21:07:26

问题


I'm making a simple web application using API's and express. But I am getting different output than expected. My output contains text including HTML tags.

Here's my 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,uk&units=metric&appid=0333cb6bfed722ca09f1062ec1ea9ca1';
  https.get(url, function(response) {
    console.log(response.statusCode + ' OK');
    response.on('data', function(data) {
      const weatherData = JSON.parse(data);
      const temp = weatherData.main.temp;
      const desc = weatherData.weather[0].description;
      const icon = weatherData.weather[0].icon;
      const imageURL = 'http://openweathermap.org/img/wn/' + icon + '@2x.png';

      res.write('<h3>The weather is currently ' + desc + '</h3>');
      //res.write('<img src=' + imageURL + '>');
      res.write(
        '<h1>The temperature in London is ' +
          '<span>' +
          temp +
          '</span> ° Celsius.</h1>'
      );
      res.send();
    });
  });
  //res.send('server is up!!!');
});

app.listen(3000, function() {
  console.log('Server started!!!');
});

output:


回答1:


Set header:res.set("Content-Type", "text/html");

Suggestion: use template string :(

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

const url =
  "https://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&appid=0333cb6bfed722ca09f1062ec1ea9ca1";
app.get("/", (req, res) => {
  https.get(url, response => {
    response.on("data", data => {
      const weatherData = JSON.parse(data);
      const temp = weatherData.main.temp;
      const { description, icon } = weatherData.weather[0];
      const imageURL = `http://openweathermap.org/img/wn/${icon}@2x.png`;

      res.set("Content-Type", "text/html");
      //OR
      res.setHeader("Content-Type", "text/html");

      res.send(`
      <h3>The weather is currently ${description}</h3>
      <img src="${imageURL}">
      <h1>The temperature in London is <span>${temp}</span> ° Celsius.</h1>
      `);
    });
  });
  //res.send('server is up!!!');
});

app.listen(3000, () => {
  console.log("Server started!!!");
});


来源:https://stackoverflow.com/questions/60919157/res-write-not-working-properly-its-showing-output-including-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!