Express:将方法的响应传递给同一post中的另一个方法

我在app.post有两个子app.post ,第一个返回一个名为customToken的string,我想把它作为parameter passing给第二个。
有人能提醒我,我错了吗?
我收到错误发送后无法设置标题。

 app.post('/.custom-token', function (req, res, nex) { var token = null; //part ONE admin.auth().createCustomToken(req.body.uid) .then(function(customToken) { console.log("Successfully created custom-token:", customToken); res.status(200).send({token: customToken}); nex(); return token = res.status(200).send({token: customToken}); }) .catch(function(error) { console.log("Error creating custom token:", error); res.status(400).send({error: error}) }); //part TWO: i need to pass in the token generated above firebase.auth().signInWithCustomToken(token) .then(function (firebaseUser) { //... }) .catch(function(error) { // ... }); }); 

你可以通过承诺链来做到这一点

  app.post('/.custom-token', function (req, res, nex) { var token = null; //part ONE admin.auth().createCustomToken(req.body.uid) .then(function(customToken) { console.log("Successfully created custom-token:", customToken); return customToken; }) .then(function(token){ // token returned in the last promise will be available here in token parameter return firebase.auth().signInWithCustomToken(token) }) .then(function(firebaseUser){ //.... //here you can send response back return res.status(200).send(); }) .catch(function(error) { console.log("Error creating custom token:", error); res.status(400).send({error: error}) }); }); 

代码中的第二部分不会等待第一部分的响应,因为asynchronous,所以标记的第二部分将为空。

你可以使用一个中间件 ,如下所示:

 const getUserToken = (req, res, next) => { admin.auth().createCustomToken(req.body.uid) .then(function(customToken) { console.log("Successfully created custom-token:", customToken); req.cutomToken = customToken; //Here will pass the control to the next handler next(); }) .catch(function(error) { console.log("Error creating custom token:", error); res.status(400).send({error: error}); res.end(); }); }); 

你在这里使用中间件

 app.post('/.custom-token',getUserToken ,function (req, res, next) { const token = req.cutomToken; firebase.auth().signInWithCustomToken(token) .then(function (firebaseUser) { //... }) .catch(function(error) { // ... }); }); 

这具有可以在多个端点上重用中间件的优点。
希望这个帮助。