javascript - NodeJS res.on() 未触发。 res.on() 不是函数

标签 javascript node.js http get

我有一个 NodeJS 代码,使用请求模块向服务器发出请求。如果我使用“http.request”,代码工作正常,但在 res.on() 上显示错误使用请求来调用电话。以下是显示错误的部分:

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();
};
.
.
.

这是我在尝试使用 ARC 或 postman 访问 url 时遇到的错误:

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

最佳答案

res.on()http 模块的事件,而不是 request 模块的事件。在您的情况下,body 包含您的数据,并且将回调函数更改为

时不需要 res.on 事件
const getReq = Request(ReqObj, function (err, res, body) {

关于javascript - NodeJS res.on() 未触发。 res.on() 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236501/

相关文章:

javascript - 使用 javascript/jquery 根据另一个选择的值显示/隐藏选择选项?

node.js - Node : force callback execution if method hangs

javascript - 如何在 Nest.js 中使用查询参数?

javascript - Ionic2 选项卡 + menuToggle

iPhone sdk,在后台运行应用程序并发送频繁的http请求

javascript - struts 2 如何从他们的 struts.jar 中将 javascript 文件包含在 jsp 中?

javascript - ContentEditable div 在 JS fiddle 中无法正常工作

javascript - 如何添加复选框以在不使用优惠券的情况下扣除一定比例?

本地存储的 Angular 异步问题

html - Favicon.ico 和静态服务器?