res.write无法正常工作。它显示的输出包括HTML标记

问题描述 投票:0回答:1

我正在使用API​​和express制作一个简单的Web应用程序。但是我得到的输出与预期不同。我的输出包含包含HTML标记的文本。

这是我的代码。

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!!!');
});

输出:enter image description here

javascript html node.js express httpwebresponse
1个回答
1
投票

设置标题:res.set("Content-Type", "text/html");

res.set("Content-Type", "text/html");
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();
© www.soinside.com 2019 - 2024. All rights reserved.