简体   繁体   中英

How do I format lines written in response.write() in NodeJS?

I am a beginner to NodeJS and express and was following a tutorial where I had to print two lines on the browser which are both headings. Since res.send() cannot be written twice, my instructor introduced us to write method. When she uses it exactly as I have used it, she gets a proper heading with the required formatting. Meanwhile, I get this:

在此处输入图像描述

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=kathmandu&appid=35ba591e9032a4e3b4a4ed1936293774&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.write("<h3>" + weatherDescription + " </h3>");
            // res.write("<h2>The temperature in Kathmandu is " + temp + " degree celcius</h2> <br/><h3>" + weatherDescription + "</h3>");
            res.send()
        })
    });
})

app.listen(3000, function () {
    console.log("Server is running in port 3000")
})

When a browser receives a response from a server, it wants to know what type of file it is. After all, what if you actually wanted to send plain text, rather than HTML? Or maybe even XML?

You can tell a browser what you'll be sending by setting the HTTP header Content-Type :

res.set('Content-Type', 'text/html');
// Or if you want to explicitly use UTF-8 and prevent a lot of decoding issues:
res.set('Content-Type', 'text/html;charset=utf-8');
// Or, a shorter way:
res.type('html');

But Express has a feature to make this easier for you so you don't need to set the Content-Type for often used formats.

res.send([body])

Sends the HTTP response.

...

When the parameter is a String, the method sets the Content-Type to “text/html”:

So if you were to change the line res.send() to res.send(''); , the content-type will be set to text/html . Express will also auto-set the content-type if you try to send an object (JSON) or Buffer (binary stream).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM