pathRegexp is not a function 引入path-to-regexp之后出错

匡翰
2023-12-01
TypeError: pathRegexp is not a function
    at new Layer (E:\webpackDemo\node_modules\_express@4.17.1@express\lib\router\layer.js:45:17)

出现这种原因呢我们追究一下源码

var pathRegexp = require('path-to-regexp');
var debug = require('debug')('express:router:layer');

/**
 * Module variables.
 * @private
 */

var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * Module exports.
 * @public
 */

module.exports = Layer;

function Layer(path, options, fn) {
  if (!(this instanceof Layer)) {
    return new Layer(path, options, fn);
  }

  debug('new %o', path)
  var opts = options || {};

  this.handle = fn;
  this.name = fn.name || '<anonymous>';
  this.params = undefined;
  this.path = undefined;
  this.regexp = pathRegexp(path, this.keys = [], opts);

其中var pathRegexp = require('path-to-regexp');
如果你引用的最新版本的path-to-regexp的话我们需要将pathRegexp变量替换为{ pathToRegexp}即是
var {pathToRegexp} = require('path-to-regexp');
同时45行的变量pathregexp也要变成pathToRegexp!!!!

还有一种办法

我们可以安装指定版本的path-to-regexp,在3.2.0的版本下使用上述所示的格式,因此在项目可以改变pathtoreexp版本影响小的情况下我们可以通过

npm i path-to-regexp@3.2.0

即可

 类似资料: