[英]Redirect REST API response to UI/Browser NodeJs/Express/Request
Not able to send response of a REST api callout to browser page using NodeJs server with Express
and Request
module.无法使用带有
Express
和Request
模块的 NodeJs 服务器将 REST api 标注的响应发送到浏览器页面。
I understand that due to asynchronous nature of callback method, response of api callout cannot be returned in typical style.我了解由于回调方法的异步性质,无法以典型样式返回 api 标注的响应。
I have tried res.send method, but it gives error res.send
is not a function.我尝试了 res.send 方法,但它给出了错误
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.
第一个问题是上面@vipul 指出的。 res was response of callout and not instance of global HttpResponse object, so send method was not available on that object.
res是标注的响应,而不是全局 HttpResponse object 的实例,因此该 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.但是由于回调 function 的异步性质,在收到调用响应时,实际的请求/响应已经返回并且请求已完成。 So removed the res.send right after callout to fix the issue.
因此,在标注后立即删除了 res.send 以解决问题。
Hopefully it will be helpful for others as well:)希望它对其他人也有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.