Reputation: 69
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?
Upvotes: 1
Views: 1658
Reputation: 69
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)
Upvotes: 0
Reputation: 24221
It does return 3, but in your example your not collecting it on your request..
Here is a modified version of your code that does the whole Request / Response, like a simple echo.
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)
Response ->
req: 3
res: 3
Upvotes: 1