代码如下:
const http = require('http');
const server = http.createServer((req, res) => {
let r = Object.create(res);
r.write('HHHHH');
r.end('OK');
});
server.listen(5000, function () {
console.log('App running!');
});
之后发送请求就没有有响应了,而且:
console.log(r.write);
console.log(res.write);
是一样的结果,r.write === res.write也为true。
try {
let o = Object.create(res);
o.end('<h1>132</h1>', 'utf-8', () => {
console.log('ok,end')
});
res.write('<h1>123456</h1>');
res.end('<h1>ok</h1>')
} catch (e) {
console.error('Error:', e.message);
}
response的结果是<h1>123456</h1><h1>ok</h1>,然后打出了‘ok, end’.
res 里的函数调用时有状态的。也就是说,不是已同样的参数调用就一定可以得到同样的结果。
这些状态时一般就是记录在 res 里的。先在,你用 r 来调用 write 跟 end ,会导致状态被写入 r 而不是 res ,从而导致 res 里的状态不正确。除了你的回调函数,没有人知道还有一个 r 存在,他们都会从 res 里读取状态。这会导致 http 的一些内部工作机制无法正常完成,从而引起各种奇怪的行为。