快递阻止我改变request.path?

时间:2016-09-04 21:26:02

标签: node.js url express middleware

我正在编写一个应用,并希望创建一个中间件,将传入的网址标准化为某种“预期”格式,它应该将/Docs/PAGE/之类的路径转换为/docs/page

我想这样做,以便以后更容易编写路径处理中间件。

这是我写的:

app.use(function(request, response, next) {
  var standardisedPath = request.path.toLowerCase().replace(/\/$/, '');
  logger.info('Standardising original path %s to %s', request.path, standardisedPath);
  request.path = standardisedPath;
  next();
});

app.get(/^\/docs.*/i, function(request, response) {
  var docPath = request.path + '.md';
  response.send(docPath);
});

但是,当我访问http://localhost/docs/PAGE/时,我的应用会以/docs/PAGE/.md回复,即使我期待/docs/page.md

1 个答案:

答案 0 :(得分:1)

假设您要将其路径中至少有一个大写字符的URL重定向到较低的等效字符:

app.use(function(request, response, next) {
  if (/[A-Z]/.test(request.url)) { // check for at least one upper case character
    return response.redirect(request.url.toLowerCase());
  }
  next();
});