当我运行下面的代码时,我得到 undefined
但在 console.log(token)
我收到了数据,如何才能得到返回的数据?response.body
作为我的引擎函数的返回值?
var request = require("request");
var randomstring = require("randomstring");
// Create Reference number
var external_ref_number = "c199-9f9-78f-967e-" + randomstring.generate(12);
//console.log(external_ref_number);
// Function to perform requests
function Engine (interface, token, request_type, external_ref_number, id, mpesa_code)
{
var data = JSON.stringify({
"message_validation":
{
"api_user": "testuser",
"api_password": "Ez[=8Ck@",
"token": token
},
"message_route": {
"interface": interface,
"request_type": request_type,
"external_ref_number": external_ref_number
},
"message_body": {
"Id": id,
"TelcoRef": mpesa_code
}
});
console.log(data);
var options = {
'method': 'POST',
'url': 'http://testurl/api/Solid/SubmitRequest',
'headers': {
'Content-Type': 'application/json'
},
body: data
};
let response;
request(options, function (error, response)
{
if (error) throw new Error(error);
var token = response.body;
response = response.body;
console.log(token);
});
return response;
}
var interface = 'TOKEN';
var token = '';
var request_type = ''
// var external_ref_number = external_ref_number;
var id = '';
var mpesa_code = '';
var data = Engine(interface, token, request_type, external_ref_number, id, mpesa_code);
console.log(data);
试试这个
var request = require("request");
var randomstring = require("randomstring");
// Create Reference number
var external_ref_number = "c199-9f9-78f-967e-" + randomstring.generate(12);
//console.log(external_ref_number);
// Function to perform requests
function Engine (interface, token, request_type, external_ref_number, id, mpesa_code, callback)
{
var data = JSON.stringify({
"message_validation":
{
"api_user": "testuser",
"api_password": "Ez[=8Ck@",
"token": token
},
"message_route": {
"interface": interface,
"request_type": request_type,
"external_ref_number": external_ref_number
},
"message_body": {
"Id": id,
"TelcoRef": mpesa_code
}
});
console.log(data);
var options = {
'method': 'POST',
'url': 'http://testurl/api/Solid/SubmitRequest',
'headers': {
'Content-Type': 'application/json'
},
body: data
};
let response;
request(options, function (error, response)
{
if (error) throw new Error(error);
var token = response.body;
response = response.body;
console.log(token);
callback(null, response);
});
//return response;
}
var interface = 'TOKEN';
var token = '';
var request_type = ''
// var external_ref_number = external_ref_number;
var id = '';
var mpesa_code = '';
Engine(interface, token, request_type, external_ref_number, id, mpesa_code, function (err, data) {
console.log(data);
});