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

Vip*_*nha 3 html javascript httpwebresponse node.js express

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

\n\n

这是我的代码。

\n\n
const express = require(\'express\');\nconst https = require(\'https\');\nconst app = express();\n\napp.get(\'/\', function(req, res) {\n  const url =\n    \'https://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&appid=0333cb6bfed722ca09f1062ec1ea9ca1\';\n  https.get(url, function(response) {\n    console.log(response.statusCode + \' OK\');\n    response.on(\'data\', function(data) {\n      const weatherData = JSON.parse(data);\n      const temp = weatherData.main.temp;\n      const desc = weatherData.weather[0].description;\n      const icon = weatherData.weather[0].icon;\n      const imageURL = \'http://openweathermap.org/img/wn/\' + icon + \'@2x.png\';\n\n      res.write(\'<h3>The weather is currently \' + desc + \'</h3>\');\n      //res.write(\'<img src=\' + imageURL + \'>\');\n      res.write(\n        \'<h1>The temperature in London is \' +\n          \'<span>\' +\n          temp +\n          \'</span> \xc2\xb0 Celsius.</h1>\'\n      );\n      res.send();\n    });\n  });\n  //res.send(\'server is up!!!\');\n});\n\napp.listen(3000, function() {\n  console.log(\'Server started!!!\');\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出: \n在此输入图像描述

\n

xde*_*akv 5

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

\n\n
\n

建议:使用模板字符串:(

\n
\n\n
const express = require("express");\nconst https = require("https");\nconst app = express();\n\nconst url =\n  "https://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric&appid=0333cb6bfed722ca09f1062ec1ea9ca1";\napp.get("/", (req, res) => {\n  https.get(url, response => {\n    response.on("data", data => {\n      const weatherData = JSON.parse(data);\n      const temp = weatherData.main.temp;\n      const { description, icon } = weatherData.weather[0];\n      const imageURL = `http://openweathermap.org/img/wn/${icon}@2x.png`;\n\n      res.set("Content-Type", "text/html");\n      //OR\n      res.setHeader("Content-Type", "text/html");\n\n      res.send(`\n      <h3>The weather is currently ${description}</h3>\n      <img src="${imageURL}">\n      <h1>The temperature in London is <span>${temp}</span> \xc2\xb0 Celsius.</h1>\n      `);\n    });\n  });\n  //res.send(\'server is up!!!\');\n});\n\napp.listen(3000, () => {\n  console.log("Server started!!!");\n});\n
Run Code Online (Sandbox Code Playgroud)\n