javascript - http request from node.js local server port 5000 to 8000 gives error -
i trying make request localhost:8000 localhost:5000 url '/servertest'. socket hang error. how fix this?
server on port 5000 (server process request):
var express = require("express"), http = require('http'); app.get('/servertest', function(req, res){ //authenticate request //send message res.writehead(200, {'content-type':'application/json'}); res.end(json.stringify({message:'hello'})); }); app.listen(5000, function() { console.log("listening on " + port); });
server on port 8000 (server makes request):
var express = require("express"), http = require('http'); var port = 8000; app.listen(port, function() { console.log("listening on " + port); makeacall(); }); function makeacall(){ var options = { host:'localhost', port: 5000, path: '/servertest', method: 'get' }; http.request(options, function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(str); }); }); }
error obtained server hosted @ port 8000:
events.js:72 throw er; // unhandled 'error' event ^ error: socket hang @ createhanguperror (http.js:1442:15) @ socket.socketonend [as onend] (http.js:1538:23) @ socket.g (events.js:175:14) @ socket.eventemitter.emit (events.js:117:20) @ _stream_readable.js:910:16 @ process._tickcallback (node.js:415:13)
when using http.request()
, have @ point call request.end()
send request.
note in example
req.end()
called.http.request()
1 must callreq.end()
signify you're done request - if there no data being written request body.
http.request(options, function(response) { // ... }).end();
or, get
requests, can use http.get()
call request.end()
.
http.get(options, function(response) { // ... });
Comments
Post a Comment