在Hello World示例中,我们使用response .send()方法发送一个简单的字符串作为响应,并关闭连接:
(req, res) => res.send('Hello World!')
如果传入一个字符串,它将内容类型头设置为text/html。
如果传入一个对象或数组,它将设置application/json内容类型头,并将该参数解析为json。
send()自动设置HTTP响应头的内容长度。
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')