Search code examples
javascriptnode.jsnode.js-streamnode.js-connectnode.js-client

res.write is not returning the expected value


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?


Solution

  • I solved it. It was a problem of visibility of variable 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)