Not able to send response of a REST api callout to browser page using NodeJs server with Express
and Request
module.
I understand that due to asynchronous nature of callback method, response of api callout cannot be returned in typical style.
I have tried res.send method, but it gives error res.send
is not a function.
Below is sample piece of that I have tried.
const options = {
url: endPoint,
method: 'POST',
headers: {
'Authorization': 'Basic',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Accept-Charset': 'UTF-8'
}
};
request(options, (err, res, body) => {
if (err) { return console.log(err); }
//want to send this body to the page.
console.log(JSON.stringify(body));
res.send(body);
});
It gives this error message,
res.send(body);
TypeError: res.send is not a function
at Request.request [as _callback]
Figured the issue. First problem was as @vipul pointed above. res was response of callout and not instance of global HttpResponse object, so send method was not available on that object. I changed the method,
request(options, (err, response, body) => {
if (err) { return console.log(err); }
//want to send this body to the page.
console.log(JSON.stringify(response.body));
// using the HttpResponse in global context.
this.res.send(JSON.parse(body));
});
Then I faced below error,
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client]
Problem was while making the callout, I was returning the response right after callout method.
.get('/authorize', (req, res) => {
console.log('Authorize Hit! '+req.query.code);
try {
//TODO: Need to utilize state to the current flow in action.
let flowDetails = flow.flowMap.get('wsf');
if(flowDetails) {
//this method makes REST API call
flowDetails.refreshToken(req, res);
//this line was the problem!! Removed it to fix the error.
res.send('Refresh Token Completed!');
}
} catch (error) {
(Object.keys(error).length === 0)?res.send(error.message):res.send(error);
}
})
But due to asynchronous nature of callback function, by the time callout response was received, actual request/response was already returned and request was completed. So removed the res.send right after callout to fix the issue.
Hopefully it will be helpful for others as well:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.