I am trying to create a simple server and a simple client with node.js using http module. Server is working fine but client is not. Please help me to find the bug...
Server Is :
var server = require('http').createServer();
server.on('request', function(req, res){
res.end("hello, world");
});
server.listen(4000);
Client Is :
var options = {
host : 'localhost',
port : 4000,
method : 'GET',
path " '/'
};
require('http').request(options, function(res){
console.log(require('util').inspect(res));
res.on('data', function(data){
console.log(data);
});
I am running them in different terminal windows as node server.js & node client.js.
I am getting below mentioned error on the client.js running terminal after around 10 mins.
events.js:72
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1473:15)
at Socket.socketOnEnd [as onend] (http.js:1569:23)
at Socket.g (events.js:175:14)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
Thanks !
I'd strongly suggest using node-fetch. It is based on the fetch API in modern browsers. Not only is it promise-based it also has an actual standard behind it. The only reason you wouldn't use fetch is if you don't like the API.
The simplest way to call an API from NodeJS server is using the Axios library. Project Setup: Create a NodeJS project and initialize it using the following command. Module Installation: Install the required modules i.e. ExpressJS and Axios using the following command.
The http requests in TypeScript can be placed by making use of a function called fetch() function. The URL of the website whose contents must be fetched or to which the contents must be posted should be passed as a parameter to the fetch() function.
The request()
method of the HTTP library will not automatically end requests, therefore they stay open, and time out. Instead, you should either end the request using req.end()
, or use the get()
method, which will do so automatically.
var http = require('http');
var req = http.request(options, function(res) {
// handle the resposne
});
req.end();
Or:
http.get(options, function(res) {
// handle the resposne
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With