我有一个使用请求模块的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或邮递员访问URL时遇到的错误:
TypeError: res.on is not a function at Request._callback at self.callback at Request.emit at Request.init at new Request
答案 0 :(得分:2)
res.on()
是http
模块而不是request
模块的事件。就您而言,body
包含您的数据,并且在将回调函数更改为
res.on
事件
const getReq = Request(ReqObj, function (err, res, body) {