http.request()
isn't working for me. I tried the same code from different computers. It doesn't give any errors, but gives the http response code 408
(which is timeout). Im so confused about why this is happening as i am doing what the documentation says.
If im doing something wrong, I'd be glad to know what to change as I can't find any information about this.
note: Servez is running on localhost:8080 so there is a server to connect to
Here is the code:
const http = require('http');
ops = {
hostname: 'localhost',
port: '8080',
path: '/',
method: 'GET'
}
http.request(ops, res => {
console.log('code: ' + res.statusCode + '\n');
dat = '';
res.on('data', chunk => {
dat += chunk;
})
res.on('end', () => {
console.log(dat);
})
})
You need to call request.end()
after using http.request()
.
Quotes from official documents:
With
http.request()
one must always callreq.end()
to signify the end of the request - even if there is no data being written to the request body.
const http = require('http');
ops = {
hostname: 'localhost',
port: '8080',
path: '/',
method: 'GET'
}
const req = http.request(ops, res => {
console.log('code: ' + res.statusCode + '\n');
dat = '';
res.on('data', chunk => {
dat += chunk;
})
res.on('end', () => {
console.log(dat);
})
})
req.end() // add this