res.write不会返回预期的值

这是代码:

var http = require('http') var options = { hostname: 'localhost', method: 'POST', port: 8000, path: '/' } var s = 3; http.request(options, (res)=>{ }).end(s+'') http.createServer((req, res)=>{ res.writeHead(200, {'Content-type': 'text/plain'}) var a = ""; req.on('data', (data)=>{ a+= data }) req.on('end', ()=>{ res.write(a) res.end() }) }).listen(8000) 

为什么当预期返回值为3时,服务器可能会向客户端返回无效信息?

它确实返回3,但在你的例子中,你不收集你的请求..

这是你的代码的一个修改版本,可以完成整个请求/响应,就像一个简单的回声。

 var http = require('http') var options = { hostname: 'localhost', method: 'POST', port: 8000, path: '/' } var s = 3; http.request(options, (res)=>{ var str = ''; //another chunk of data has been recieved, so append it to `str` res.on('data', function (chunk) { str += chunk; }); //the whole response has been recieved, so we just print it out here res.on('end', function () { console.log('res: ' + str); }); }).end(s+'') http.createServer((req, res)=>{ res.writeHead(200, {'Content-type': 'text/plain'}) var a = ""; req.on('data', (data)=>{ a+= data }) req.on('end', ()=>{ console.log('req: ' + a) res.write(a) res.end() }) }).listen(8000) 

回应 – >

 req: 3 res: 3 

我解决了它。 这是variablesa的可见性问题。

 var http = require('http') var a = ''; var options = { hostname: 'localhost', method: 'POST', port: 8000, path: '/' } var s = 3; http.request(options, (res)=>{ }).end(s+'') http.createServer((req, res)=>{ res.writeHead(200, {'Content-type': 'text/plain'}) req.on('data', (data)=>{ a+= data }) req.on('end', ()=>{ res.write(a) res.end() }) }).listen(8000)