Javascript 如何格式化NodeJS中response.write()中写入的行?

Javascript 如何格式化NodeJS中response.write()中写入的行?,javascript,node.js,express,web,Javascript,Node.js,Express,Web,我是NodeJS和express的初学者,在学习一个教程时,我不得不在浏览器上打印两行标题。由于res.send()不能写两次,所以我的导师向我们介绍了write方法。当她像我一样使用它时,她会得到一个带有所需格式的正确标题。同时,我明白了: const express=require(“express”); const https=require(“https”); 常量app=express(); 应用程序获取(“/”,函数(请求,恢复){ 常量url=”https://api.openw

我是NodeJS和express的初学者,在学习一个教程时,我不得不在浏览器上打印两行标题。由于res.send()不能写两次,所以我的导师向我们介绍了write方法。当她像我一样使用它时,她会得到一个带有所需格式的正确标题。同时,我明白了:

const express=require(“express”);
const https=require(“https”);
常量app=express();
应用程序获取(“/”,函数(请求,恢复){
常量url=”https://api.openweathermap.org/data/2.5/weather?q=kathmandu&appid=35ba591e9032a4e3b4a4ed1936293774&units=metric"
https.get(url、函数(响应){
console.log(response.statusCode)
响应。关于(“数据”,函数(数据){
const weatherdata=JSON.parse(数据)
常数温度=weatherdata.main.temp
const weatherDescription=weatherdata.weather[0]。说明
res.write(“+weatherDescription+”);
//res.write(“加德满都的温度为“+temp+”摄氏度
“+weatherDescription+”); res.send() }) }); }) 应用程序侦听(3000,函数(){ 日志(“服务器正在端口3000中运行”) })
当浏览器收到服务器的响应时,它想知道它是什么类型的文件。毕竟,如果你真的想发送纯文本而不是HTML呢?或者甚至是XML

您可以通过
内容类型
告诉浏览器要发送的内容:

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');
但是Express有一个功能可以让您更轻松,因此您无需为常用格式设置
内容类型

发送HTTP响应

当参数为字符串时,该方法将内容类型设置为“text/html”:


因此,如果要将行
res.send()
更改为
res.send(“”)
,内容类型将设置为
text/html
。如果您尝试发送对象(JSON)或缓冲区(二进制流),Express也会自动设置内容类型。

成功了。谢谢。但我也想知道我发布的代码是如何为我的导师工作的?她没有使用你提到的任何东西。你确定在
send
方法中没有遗漏两个引号吗?很容易将
send(“”)
误认为
send()
(最后提到的方法)。不,我没有。但我所学的课程差不多有两年了。
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');