我正在node中使用Express框架.js具有一些中间件功能:

var app = express.createServer(options);
app.use(User.checkUser);

我可以使用带有附加参数的.use函数,以便仅在特定路径上使用此中间件:

app.use('/userdata', User.checkUser);

那么,除了根路径,所有路径都可以使用吗?

我在想这样的事情:

app.use('!/', User.checkUser);

所以除了根路径外,总是调用User.checkUser.

推荐答案

我会将checkUser中间件添加到我的所有路径中,除了主页.

app.get('/', routes.index);
app.get('/account', checkUser, routes.account);

app.all('*', checkUser);
    
function checkUser(req, res, next) {
  if ( req.path == '/') return next();

  //authenticate user
  next();
}

You could extend this to search f或 the req.path in an array of non-authenticated paths:

function checkUser(req, res, next) {
  const nonSecurePaths = ['/', '/about', '/contact'];
  if (nonSecurePaths.includes(req.path)) return next();

  //authenticate user
  next();
}

Node.js相关问答推荐

查找或展开Sharepoint页面标题区域图像- Microsoft Curve API

在Cypress测试文件中获取项目根路径

可以删除一个mongodb catch块

Express 4.18正文解析

从MongoDB获取Tree数据

AWS-ROUTE 53指向S3存储桶,错误是别名目标名称不在目标区域内

使用AWS SDK for JavaScript V3将图像从node.js上传到s3 bucket

通过 Node js 中的 TBA 执行 netsuite REST upsert 操作出现 401 错误

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

如何从mongoose 对象内嵌套的数组中提取数组元素?

如何在 JavaScript 中显示多维数组中使用的一维数组的变量名?

将 null 推入管道后,node.js 可写完成未发出

Typescript 正则表达式:过滤器返回空

如何获取需要加载cheerio的网站部分数据?

在路由上使用中间件时,Nodejs Express 应用程序失败

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

图像存储在后端文件夹中,但使用 multer 和 react.js 在前端找不到

`npm install` 以Killed结尾

eslint - vscode 的可选链接错误

为什么 Node.js 没有原生 DOM?