Tho*_*mas 60 middleware routes node.js express
我在node.js中使用Express框架和一些中间件函数:
var app = express.createServer(options);
app.use(User.checkUser);
Run Code Online (Sandbox Code Playgroud)
我可以使用.use带有附加参数的函数仅在特定路径上使用此中间件:
app.use('/userdata', User.checkUser);
Run Code Online (Sandbox Code Playgroud)
是否可以使用路径变量,以便中间件用于除特定路径之外的所有路径,即根路径?
我在考虑这样的事情:
app.use('!/', User.checkUser);
Run Code Online (Sandbox Code Playgroud)
所以User.checkUser总是被调用除了根路径.
cho*_*ovy 96
我会将checkUser中间件添加到我的所有路径,但主页除外.
app.get('/', routes.index);
app.get('/account', checkUser, routes.account);
Run Code Online (Sandbox Code Playgroud)
要么
app.all('*', checkUser);
function checkUser(req, res, next) {
if ( req.path == '/') return next();
//authenticate user
next();
}
Run Code Online (Sandbox Code Playgroud)
您可以使用下划线扩展它,以在非经过身份验证的路径数组中搜索req.path:
function checkUser(req, res, next) {
var _ = require('underscore')
, nonSecurePaths = ['/', '/about', '/contact'];
if ( _.contains(nonSecurePaths, req.path) ) return next();
//authenticate user
next();
}
Run Code Online (Sandbox Code Playgroud)
User.checkUser注册一个新的辅助函数,而不是直接注册为中间件,例如checkUserFilter,在每个URL上调用它,但仅在给定的URL上将执行传递给userFiled`.例:
var checkUserFilter = function(req, res, next) {
if(req._parsedUrl.pathname === '/') {
next();
} else {
User.checkUser(req, res, next);
}
}
app.use(checkUserFilter);
Run Code Online (Sandbox Code Playgroud)
从理论上讲,您可以提供正则表达式路径app.use.例如:
app.use(/^\/.+$/, checkUser);
Run Code Online (Sandbox Code Playgroud)
在Express 3.0.0rc5上尝试过,但它不起作用.
也许我们可以打开一张新票并将其作为特色推荐?
您也可以为每个路由设置一个中间件.
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
Run Code Online (Sandbox Code Playgroud)
小智 5
用
app.use(/^(\/.+|(?!\/).*)$/, function(req, resp, next){...
Run Code Online (Sandbox Code Playgroud)
这会传递除 / 之外的任何 url。除非,它对我有用。
一般来说
/^(\/path.+|(?!\/path).*)$/
Run Code Online (Sandbox Code Playgroud)
(请参阅如何否定正则表达式中的特定单词?)
希望这可以帮助
解决方案是使用设置api和中间件的顺序。在你的情况下,它一定是这样的。
var app = express.createServer(options);
// put every api that you want to not use checkUser here and before setting User.checkUser
app.use("/", (req, res) => res.send("checkUser middleware is not called"));
app.use(User.checkUser);
// put every api that you want use checkUser
app.use("/userdata", User.checkUser, (req, res) =>
res.send("checkUser called!")
);
Run Code Online (Sandbox Code Playgroud)
这是一个完整的例子。
const express = require("express");
const app = express();
const port = 3002;
app.get("/", (req, res) => res.send("hi"));
app.use((req, res, next) => {
console.log("check user");
next();
});
app.get("/checkedAPI", (req, res) => res.send("checkUser called"));
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56957 次 |
| 最近记录: |