如何使用Express将响应发回给客户端
在Hello World的例子中,我们使用Response.send() 方法来发送一个简单的字符串作为响应,并关闭连接。
(req, res) => res.send('Hello World!')
如果你传入一个字符串,它会将Content-Type 头部设置为text/html 。
如果你传入一个对象或一个数组,它会设置application/json Content-Type 头,并将该参数解析为JSON。
send() 自动设置 HTTP响应头。Content-Length
send() 还会自动关闭连接。
使用end()来发送一个空响应
另一种发送响应的方法,没有任何主体,它是通过使用Response.end() 方法。
设置HTTP响应状态
使用Response.status():
或
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')