res.write无法正常工作.它显示包含HTML标签的输出 [英] res.write not working properly. It's showing output including HTML tags

查看:59
本文介绍了res.write无法正常工作.它显示包含HTML标签的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的代码.

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

输出:

推荐答案

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

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

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

这篇关于res.write无法正常工作.它显示包含HTML标签的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆