You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Express中指定/reset/后匹配任意字符串的路由

解决Express中间件中匹配/reset/:token路由的问题

这个问题我之前也碰到过——你直接用字符串'/reset/*'和request.path做比对是行不通的,因为request.path返回的是实际请求的完整路径字符串(比如/reset/4c1ff3ada180bea9da6333fd9555dd100828d530),它不会识别通配符*,只有当路径完全等于'/reset/*'时才会匹配,显然这不是你要的效果。

下面给你两种简单且有效的解决方案:

方案1:使用字符串startsWith判断

这是最直观的方式,只需要检查请求路径是否以/reset/开头即可,代码修改如下:

'use strict';
var express = require('express');

module.exports = {
  isLoginCheck: function (request, response, next) {
    // 判断是否是reset路径
    const isResetPath = request.path.startsWith('/reset/');
    
    if (!request.session.user && 
        request.path !== '/index' && 
        request.path !== '/forgot-pass' && 
        request.path !== '/forgot' && 
        !isResetPath) {
      response.redirect('/index');
    } else {
      next();
    }
  },
};

方案2:使用正则表达式匹配(更严谨)

如果你想确保匹配的路径严格符合/reset/随机token的格式(比如你的token是十六进制字符串),可以用正则表达式来精准匹配,示例代码:

'use strict';
var express = require('express');

module.exports = {
  isLoginCheck: function (request, response, next) {
    // 正则匹配:/reset/后跟至少一个字符(可根据token格式调整)
    // 如果你的token是固定40位十六进制,可改成 /^\/reset\/[a-f0-9]{40}$/
    const isResetPath = /^\/reset\/.+$/.test(request.path);
    
    if (!request.session.user && 
        request.path !== '/index' && 
        request.path !== '/forgot-pass' && 
        request.path !== '/forgot' && 
        !isResetPath) {
      response.redirect('/index');
    } else {
      next();
    }
  },
};

两种方案都能解决你的问题,其中startsWith更简洁,正则表达式则能提供更精准的路径校验,你可以根据自己的需求选择。

内容的提问来源于stack exchange,提问作者Ayan Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:59:25