[英]Best practice for passing data from from a asynchronous call in nodejs with correct fallback routing structure
I have a request function that makes a call to an endpoint and gets data from it.我有一个请求函数,可以调用端点并从中获取数据。 Then i pass this data to an hbs template for rendering but due to asyncronycity the array passed to template is empty.
然后我将此数据传递给 hbs 模板进行渲染,但由于异步性,传递给模板的数组为空。 What is the right way to do it.
什么是正确的方法。 Please help.
请帮忙。 The code snippet is below.
代码片段如下。
app.get("/verifier", keycloak.protect('verifier'), (req, res) => {
cirRes = cirJSON.parse(cirJSON.stringify(res))
//the req object is a circular object so you cannot convert it to json normaly wihtout data loss.
allUser = []
access_token = cirRes.req.kauth.grant.access_token.token
var options = { method: 'GET',
url: 'http://localhost:8080/auth/admin/realms/create_user_realm/users',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
Host: 'localhost:8080',
Accept: '*/*',
Authorization: `Bearer ${ access_token }` } }
request(options, function (error, response, body) {
if (error) throw new Error(error);
data = JSON.parse(body)
for (user in data){
allUser.push(data[user])
}
//console.log(allUser)
})
if (res.statusCode != 200) {
res.redirect('/logout')
}
console.log(allUser)
res.render('verifier', {"users": allUser})
})
The allUser comes out to be an empty array in above code. allUser 在上面的代码中是一个空数组。
edit >>>>编辑 >>>>
This question was closed given the answer in this thread.鉴于此线程中的答案,此问题已关闭。 How do I return the response from an asynchronous call?
如何从异步调用返回响应? It covers different ways to make asynchronous requests.
它涵盖了发出异步请求的不同方法。
Going through the same i made this change in code经历了同样的事情,我在代码中做了这个改变
app.get("/verifier", keycloak.protect('verifier'), (req, res) => {
cirRes = cirJSON.parse(cirJSON.stringify(res))
//the req object is a circular object so you cannot convert it to json normaly wihtout data loss.
//console.log(cirRes.req.kauth.grant.access_token.token)
allUser = []
access_token = cirRes.req.kauth.grant.access_token.token
var options = { method: 'GET',
url: 'http://localhost:8080/auth/admin/realms/create_user_realm/users',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
Host: 'localhost:8080',
Accept: '*/*',
Authorization: `Bearer ${ access_token }` } }
request(options, function (error, response, body) {
if (error) { throw new Error(error) }
data = JSON.parse(body)
for (user in data){
allUser.push(data[user])
}
//console.log(allUser)
res.render('verifier', {"users": allUser})
})
if (res.statusCode != 200) {
res.redirect('/logout')
}
})
This works fine, but is the correct according to best practices of nodeJS and what is the best practice for this in nodeJS so that some fallback mechanism is there to render even if an error occurs in call.这工作正常,但根据 nodeJS 的最佳实践是正确的,nodeJS 中的最佳实践是什么,以便即使调用中发生错误,也有一些回退机制可以呈现。
Move your res.render()
and res.redirect()
calls so they are inside the callback function of your request()
call.移动
res.render()
和res.redirect()
调用,使它们位于request()
调用的回调函数内。 That's how you use asynchronously provided information in express when you want to send it to a user's browser or API client.这就是当你想将它发送到用户的浏览器或 API 客户端时,你如何在 express 中使用异步提供的信息。
It's perfect.这是完美的。 you need to add option variable in try-catch block.
您需要在 try-catch 块中添加选项变量。
try{
var options = { method: 'GET',
url: 'http://localhost:8080/auth/admin/realms/create_user_realm/users',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
Host: 'localhost:8080',
Accept: '*/*',
Authorization: `Bearer ${ access_token }` } }
request(options, function (error, response, body) {
if (error) { throw new Error(error) }
data = JSON.parse(body)
for (user in data){
allUser.push(data[user])
}
//console.log(allUser)
res.render('verifier', {"users": allUser})
})
if (res.statusCode != 200) {
res.redirect('/logout')
}
}catch(e){
throw(e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.