1

This is the code:

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)

Why might the server be returning invalid information to the client when a return value of 3 is expected?

4

2 回答 2

1

它确实返回 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
于 2017-08-22T23:49:53.133 回答
0

我解决了。这是变量a的可见性问题。

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)
于 2017-08-23T10:26:27.670 回答