📜  Node.js response.writeContinue() 方法(1)

📅  最后修改于: 2023-12-03 14:44:40.172000             🧑  作者: Mango

Node.js response.writeContinue() 方法

Node.js中的 response.writeContinue() 方法用于发送一个 HTTP/1.1 100 Continue 状态码给客户端,表示可以继续发送请求body。该方法通常用于在客户端发送大型请求body之前,服务器会发送这个状态码进行通知,以便客户端可以继续发送。

语法
response.writeContinue(callback)
参数
  • callback: 可选。当请求继续时调用的回调函数。
返回值

该方法没有返回值。

示例
const http = require('http');

const server = http.createServer((req, res) => {
  // 发送100 Continue
  res.writeContinue();
  
  // 等待请求body并返回
  req.on('data', (chunk) => {
    res.write(chunk);
  });
  req.on('end', () => {
    res.end();
  });
});

server.listen(3000);

在上面的示例中,服务器接收客户端的请求,并在请求body开始之前发送了一个 HTTP/1.1 100 Continue 状态码。然后服务器使用 req.on('data', ...) 监听请求body,将它写入响应。当完成时,服务器调用 res.end() 结束响应。

如果没有调用 res.writeContinue() 方法,则客户端会一直等待服务器发送响应。在发送大型请求body时,这可能会导致客户端超时。因此,建议在请求body开始之前使用 res.writeContinue() 方法发送 HTTP/1.1 100 Continue 状态码进行通知。

以上就是关于 Node.js 中 response.writeContinue() 方法的介绍。希望对你有所帮助!