如何将数据从Express JS中的子应用程序/子模块发送回安装点(我认为这是正确的词)通常是app.js

时间:2019-02-11 15:43:39

标签: node.js express

我将应用拆分为子应用,所有子应用都安装在app.js上

//app.js
const express = require('express');
const app = express();
const auth = require('./api/auth') //sub-app auth.js;
var tokenid = '';
app.use('/auth' , auth ,(req , res ,next)=>{

//I would like to receive the tokenid from auth.js and use it in   
//subsequent calls. 

})

app.listen(8080);
module.exports = app;

这是我的auth.js

//auth.js //In api directory
const express = require('express')
const router = express.Router()
var Tokenid = '';
router.get('/' , (req , res ,next)=>{

//I made request to external api and got the Tokenid successfully.

//How can i send this Tokenid to app.js to use it in 
//further calls from app.js    

})
module.exports = router

我需要在app.js中使用Tokenid,以便可以在其他子应用程序对外部api的进一步调用中使用它,是否有更好的方法做到这一点,请建议我!

谢谢。

编辑 谢谢@estus 完整的代码

//auth.js //In api directory
const express = require('express')
const router = express.Router()
var Tokenid = '';
router.get('/' , (req , res ,next)=>{

//I made request to external api and got the Tokenid successfully.

req.app.locals.tokenid = ExternalApiTokenid
//To use it in other routes : app.locals.tokenid    

})
module.exports = router

0 个答案:

没有答案