使用Express发送响应

如何使用Express向客户端发送响应 在"Hello World"示例中,我们使用Response.send()方法发送一个简单的字符串作为响应,并关闭连接: (req, res) => res.send('Hello World!') 如果传入的是字符串,它会将Content-Type头设置为text/html。 如果传入的是对象或数组,它会将Content-Type头设置为application/json,并将该参数解析为JSON。 send()会自动设置Content-LengthHTTP响应头。 send()还会自动关闭连接。 使用end()发送空响应 发送没有任何内容的响应的另一种方法是使用Response.end()方法: res.end() 设置HTTP响应状态 使用Response.status(): res.status(404).end() 或者 res.status(404).send('File not found') sendStatus()是一个快捷方式: res.sendStatus(200) // === res.status(200).send('OK') res.sendStatus(403) // === res.status(403).send('Forbidden') res.sendStatus(404) // === res.status(404).send('Not Found') res.sendStatus(500) // === res.status(500).send('Internal Server Error')