我相对较新Node.js
,我正在创建一个服务器,该服务器将接受POST
来自移动应用程序的请求,该应用程序的主体包含凭据,然后将通过GET
另一台服务器进行验证。如果GET
响应验证凭据,则提取 UID 并调用firebase admin SDK
以创建自定义令牌。下面是一段代码和两个被调用以(a)
验证凭据并(b)
生成自定义令牌的函数。
//Listen for app to POST Credential
app.post('/', function(request, response) {
console.log('Request Body: ',request.body);
var Credential = request.body;
//Validate Credential
validateCredential(Credential)
//Get Authorization Token
getToken(userID)
//Return Token for POST Response
response.set('Content-Type','Text');
response.end(firebaseAuthToken);
});
//Create listener for POST function
app.listen(port, function() {
console.log('AuthServer is running and listening on port '+port);
});
//Function to Validate Credential
async function validateCredential(crdntl) {
//Call Service to validate Credential received
axios({
method: 'get',
url: 'https://.....',
})
.then(function(response) {
...check credential validation data
})
.catch(function (error) {
console.log('ERROR: Unable to Validate Credential');
//Unable to create Validate Credential so return error message for POST response
return ('ERROR1');
});
}
async function getToken(uid) {
admin.auth().createCustomToken(uid)
.then(function(customToken) {
var AuthToken = customToken;
var decoded = jwt.decode(AuthToken);
console.log('Decoded Token: '+'\n',decoded);
//Return Authorization Token for POST response
return (AuthToken);
})
.catch(function(error) {
console.log('ERROR: Unable to Create Custom Token', error);
//Unable to create Token so return error message for POST response
return ('ERROR2');
});
}
}
我需要返回validateCredential函数的结果并将其结果传递给getToken函数并返回其结果,以便可以发送 POST 响应。我知道这些函数是异步的,我可以将它们与回调或承诺链接起来。
真正的问题是如何让 POST 响应等待来自 getToken 函数的回调,因为最终目标是将自定义令牌传递回 POST 响应正文中的移动应用程序。任何帮助,将不胜感激。
你的validateCredential
和getToken
函数已经async
是返回promise的,要在POST
函数中等待这些函数发送响应,你必须创建POST
函数async
然后await
在调用这两个函数时使用关键字,当你使用await
函数执行时,等待函数响应被Promise
解析,这是示例代码。
//Listen for app to POST Credential
app.post('/', async function(request, response) {
console.log('Request Body: ',request.body);
var Credential = request.body;
//Validate Credential
var userId = await validateCredential(Credential) //Waits until userId comes
//Get Authorization Token
var firebaseAuthToken = await getToken(userID) //waits until Token comes
//Return Token for POST Response
response.set('Content-Type','Text');
response.end(firebaseAuthToken);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句