最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - res.write not working properly. It's showing output including HTML tags - Stack Overflow

programmeradmin0浏览0评论

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 =
    '.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 = '/' + 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:

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/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/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:

Share Improve this question asked Mar 29, 2020 at 18:48 Vipul SinhaVipul Sinha 8501 gold badge12 silver badges16 bronze badges 3
  • which article you are following to achieve res.write in that way? – Zain Ul Abideen Commented Mar 29, 2020 at 18:50
  • I'm following udemy course of plete web development 2020 by Angela Yu. – Vipul Sinha Commented Mar 29, 2020 at 18:51
  • I also had this issue – WHOATEMYNOODLES Commented Nov 5, 2020 at 2:44
Add a ment  | 

4 Answers 4

Reset to default 5

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/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/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!!!");
});
const express=require("express");
const https=require("https");
const app=express();

app.get("/",function(req,res){
const url="https://api.openweathermap/data/2.5/weather?appid=d44d8ad5bbf91d43d54c12a154921930&q=surat&units=metric"
    https.get(url,function(response){
        console.log(response.statusCode);

        response.on("data",function(data){
        
            const weatherData=JSON.parse(data)
          
            const temp=weatherData.main.temp
            
            const weatherDescription=weatherData.weather[0].description
            

            const feels_like=weatherData.main.feels_like
           
            res.setHeader("Content-Type", "text/html");
            res.write("<h3>The Weather is currently "+weatherDescription+"</h3>");
            res.write("<h1>The temperature in Surat is :"+temp+" Degree Celcius</h1>");
            res.send() 

        })
    })
    //res.send("Server is up and running")
})


app.listen(3000,function(){
    
    console.log("Server is rinning on port 3000.");
})

Just put res.set or res.setHeader with content type before res.write will give you the solution.

res.set("Content-Type", "text/html");
res.write('<h3>The weather is currently ' + desc + '</h3>');
// or
res.setHeader("Content-Type", "text/html");
res.write('<h3>The weather is currently ' + desc + '</h3>');

const express = require("express");
const https = require("https");
const app = express();
app.get("/", function (req, res) {
    const url = "https://api.openweathermap/data/2.5/weather?q=London&appid=f7b456d9c3a2e6e39c6f1ac945c5a16b&units=metric";
    https.get(url, function (response) {
        console.log(response.statusCode);
        response.on("data", function (data) {
            {
                const weatherData = JSON.parse(data);
                const temp=weatherData.main.temp;
                const weatherDescription=weatherData.weather[0].description;
                res.set("Content-Type", "text/html");
                console.log(weatherDescription);
                res.write("<h3>The weather is currently "+weatherDescription+" </h3>")
                res.write("<h1>The temperature in London is "+temp+" degrees Celcius</h1>")
                res.send();
            }
        })
    });
})
app.listen(3000, function () {
    console.log("Server is running on port 3000");
})

The line res.set("Content-Type", "text/html") is setting the Content-Type header of the response to indicate that the response body will be in HTML format. This line ensures that the browser or client receiving the response knows how to interpret and display the content correctly.

The res.set() function in Express is used to set response headers. In this case, setting the Content-Type header to "text/html" informs the client that the response will be in HTML format.

When the client receives the response, it checks the Content-Type header and processes the response accordingly. In this case, since the Content-Type is set to "text/html", the client (typically a web browser) will interpret the response as HTML and render it accordingly.

By setting the Content-Type header to "text/html", the browser knows that it should expect HTML content, and it will render the response as HTML, displaying the weather information correctly with the appropriate formatting.

发布评论

评论列表(0)

  1. 暂无评论