我正在使用带有 nodejs 的 Typescript。callback function我有,并且当我控制台时,我正在将数据作为主体中的对象获取。我想在ctx.body. 我可以将其推入object其他variable然后传递给ctx.body吗?
router.post('/api/send_otp', async (ctx: Koa.Context, next: () => Promise<any>) => {
var phone = ctx.request.body.phone;
if (!phone) {
ctx.body = {
message: "Please enter phone number",
};
} else {
var options = {
url: '',
method: 'POST',
auth: {
'user': '',
'pass': ''
},
};
const callback = function(error, response, body) {
if (response) {
console.log(body); // Getting data here
}else{
console.log('error',error);
}
};
request(options,callback);
ctx.body = {
data: body, //I want data here
}
});
Run Code Online (Sandbox Code Playgroud)
您可以将回调样式转换为 Promise 并像这样执行
const options = {
"url": "",
"method": "POST",
"auth": {
"user": "",
"pass": ""
}
};
function makeCall() {
return Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (response) {
resolve(body);
} else {
reject(error);
}
});
});
}
makeCall
.then(body => {
ctx.body = {
"data": body // I want data here
};
});
Run Code Online (Sandbox Code Playgroud)
请注意,请求不再被维护,因此最好使用一些现代包,例如got和axios。