Search code examples
javascriptnode.jsnode.js-connectnode.js-client

Http.request in node.js


This is my code in node js:

var http = require('http');

var options = { 
    host : '127.0.0.1',
    port: 8124,
    path: '/',
    method: 'GET'
};

http.request(options, function(res){    
    console.log("Hello!");  
}).end();

process.on('uncaughtException', function(err){  
    console.log(err);
});

When I compile it, the compiler shows me the following error:

enter image description here

edit: with the express works, but if I wanted to make it work without express how could I do?


Solution

  • To resolve this issue, it was enough to add to the previous code, the server code.

    var http = require('http');
    
    var options = { 
        host : '127.0.0.1',
        port: 8124,
        path: '/',
        method: 'GET'
    };
    
    http.request(options, function(res){    
        console.log("Hello!");  
    }).end();
    
    process.on('uncaughtException', function(err){  
        console.log(err);
    });
    
    http.createServer((req, res)=>{ 
        res.writeHead(200, {'Content-type': 'text/plain'})
        res.end()   
    }).listen(8124)