我使用node.js和express,我有以下路由和中间件函数isMobile.如果我不使用return next(); 在isMobile函数中,app会卡住,因为nodejs不会移动到下一个函数.
但我需要isMobile函数来返回一个值,以便我可以在app.get中进行相应的处理.有任何想法吗?
app.get('/', isMobile, function(req, res){
// do something based on isMobile return value
});
function isMobile(req, res, next) {
var MobileDetect = require('mobile-detect');
md = new MobileDetect(req.headers['user-agent']);
//return md.phone(); // need this value back
return next();
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Far*_*hat 23
你有几个选择:
将值附加到req对象:
app.get('/', isMobile, function(req, res){
// Now in here req.phone is md.phone. You can use it:
req.phone.makePrankCall();
});
function isMobile(req, res, next) {
var MobileDetect = require('mobile-detect');
md = new MobileDetect(req.headers['user-agent']);
req.phone = md.phone();
next();// No need to return anything.
}
Run Code Online (Sandbox Code Playgroud)
这是多少快速/连接中间件传递值.像bodyParser一样附加body属性来请求对象,或者会话中间件附加会话属性来请求obejct.
虽然请注意,您必须小心,没有其他库使用该属性,因此没有冲突.
不要把它变成中间件,只需直接使用该功能即可.如果它不像上面那样异步,并且不会全局用于所有路线(不会有这样的东西:) app.use(isMobile),这也是一个很好的解决方案:
app.get('/', function(req, res){
var phone = isMobile(req);
phone.makePrankCall();
});
function isMobile(req) {
var MobileDetect = require('mobile-detect');
md = new MobileDetect(req.headers['user-agent']);
return md.phone();
}
Run Code Online (Sandbox Code Playgroud)如果计算成本很高,并且您可以在多个中间件中使用它,则可以使用weakmap对其进行缓存.