这个问题通常是由于在发送响应后发送更多的头信息或尝试执行重定向而引起的。解决方法是确保在向客户端发送响应后不再发送任何头信息或尝试进行重定向。以下是一个示例代码:
app.get('/example', function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.write('Hello, world!');
res.end();
});
// 不好的重定向示例
app.get('/redirect', function(req, res) {
res.redirect('/example');
res.setHeader('Location', '/example');
res.end();
});
// 好的重定向示例
app.get('/redirect', function(req, res) {
res.redirect('/example');
});
在不好的重定向示例中,两行代码都会执行,因此客户端会收到两个带有不同位置头信息的响应,这会导致“Cannot set headers after they are sent to the client”错误。在好的重定向示例中,只有一行代码执行,因此客户端只会收到一个带有正确位置头信息的响应。