javascript - res.write 无法正常工作。它显示包含 HTML 标签的输出

标签 javascript html node.js express httpwebresponse

我正在使用 API 和 express 制作一个简单的网络应用程序。 但我得到的输出与预期不同。我的输出包含包含 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

最佳答案

设置标题: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!!!");
});

关于javascript - res.write 无法正常工作。它显示包含 HTML 标签的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60919157/

相关文章:

javascript - 隐藏/显示具有相同类别的所有 div ID 上的内容

javascript - 如何解决模板包错误?

c# - 为什么 img src 不能作为 <asp :Image ImageUrl does 工作

javascript - 如何调试 Jsx 代码

javascript - 如何为正则表达式添加条件?

javascript - 我如何在 jquery 中获得警告框?

javascript - 在使用 ajax 显示之前加载 TXT 文件

html - 不能在 svg 的中心制作 g

Node.js 议程 : how to retry jobs after failure?

javascript - 如何确保我不会将内容替换为旧响应?