Reputation: 3172
I am trying to do the following: Send a request. The server should print the request body and then send a small response. The request's callback should print the response from the server.
Somewhere along the line I have done something wrong. I can't figure out what it is.
Server:
var http = require('http');
var server = http.createServer(function (request, response) {
var reqBody = '';
request.on('data', function (chunk) {
reqBody += chunk;
});
request.on('end', function (chunk) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("<h1>Hello world!</h1>");
console.log(reqBody);
});
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Request:
var http = require('http');
var options = {
host: '127.0.0.1',
port: 8000,
path: '/',
method: 'GET',
headers: {"Content-Type": "text/plain"}
};
var reqBody = "<h1>Hello!</h1>";
var req = http.request(options, function(res) {
res.setEncoding('utf8');
var resBody = '';
res.on('data', function (chunk) {
resBody += chunk;
});
res.on('end', function (chunk) {
console.log('response: ' + resBody);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(reqBody);
req.end();
Edit: The error which I am getting
problem with request: socket hang up
Upvotes: 1
Views: 3552
Reputation: 13198
The problem is with combining req.write
with GET
, which is body-less. Comment out the second-to-last line of your request and it will be fine.
Upvotes: 3