Search code examples
javascriptnode.jshttpget

NodeJS res.on() is not triggered. res.on() not a function


I have a NodeJS code using request module to make a request to the server. The code works fine if I use 'http.request' but shows error on res.on() while using request to make the call. Following is the part showing the error:

const Request = require("request");
.
.
.
function getRequiredTime(lc, lat, lon, id, response, callback) {

    const start = new Date();
    const ReqObj = {
        host: 'localhost',
        port: process.env.PORT,
        path: '/something/' + lc + '/' + lat + '/' + lon +'/' + id,
        method: 'GET'
    };


    const RespObj = {};
    const requestBody = {};

    requestBody.id = id;
    requestBody.app_name = "someApp";
    requestBody.hostname = ReqObj.hostname;
    requestBody.path = ReqObj.path;
    requestBody.msg = "Some message";
    requestBody.body = "";
    logger.info(JSON.stringify(requestBody));

    const getReq = Request(ReqObj, function (res) {

        if (res.statusCode === 400) {
            response.send("Some message");
        } else if (res.statusCode === 500) {
            response.send("Some message");
        } else if (res.statusCode === 501) {
            response.send("Some message");
        } else {

            let duration = parseInt(15);

            res.on('data', function (durationtime) {
                const end = new Date();
                const end = *****;
                const responseDat = {
                    'id': id,
                    'start': start,
                    'end': end,
                    'time': end,
                    'service_name': 'someName'
                };

                duration += parseInt(durationtime);
                const time = parseInt(duration);
                RespObj.id = id;
                RespObj.app_name = "getApp";
                RespObj.msg = "Some message";
                RespObj.body = time;
                logger.info(JSON.stringify(RespObj));
                callback(time);

            });

            res.on('error', function (error) {
                logger.error(`ERROR`);                

            });
        }
    });
    getReq.end();
};
.
.
.

This is the error I am getting when trying to hit the url with ARC or postman:

TypeError: res.on is not a function at Request._callback
at self.callback
at Request.emit 
at Request.init
at new Request

Solution

  • res.on() is an event of http module, not request module. In your case, body contains your data and no need res.on event when change your callback function to

    const getReq = Request(ReqObj, function (err, res, body) {