A regex works fine with Express Route Tester but it failed when it used with NodeJS

225 Views Asked by At

I used express in a NodeJs project, and i want to be able to request my server with theses routes :

/dogs
/pinguin
/bear
/wolf
/cat
/rat

I use a regex for this (http://forbeslindesay.github.io/express-route-tester/) : Express Route Tester

It works correctly with express route tester but it failed when i tried with NodeJS

My code :

var express = require('express');
var app = express()

app.get("\/(dogs|pinguin|bear|wolf|cat|rat)", function (req, res) {
  res.send('dogs or pinguin');
});

error :

return new RegExp(path, flags);
         ^

SyntaxError: Invalid regular expression: /^\/(?(?:([^\/]+?))|pinguin|bear|wolf|cat|rat)\/?$/: Invalid group
    at new RegExp (<anonymous>)
    at pathtoRegexp (C:\Users\Corentin\node_modules\path-to-regexp\index.js:128:10)
    at new Layer (C:\Users\Corentin\node_modules\express\lib\router\layer.js:45:17)
    at Function.route (C:\Users\Corentin\node_modules\express\lib\router\index.js:500:15)
    at Function.app.<computed> [as get] (C:\Users\Corentin\node_modules\express\lib\application.js:481:30)
    at Object.<anonymous> (C:\Users\Corentin\Documents\mesProjets\mdm\mdm-api\routes.js:36:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
1

There are 1 best solutions below

0
On

try with the below code

app.get(/^\/(dogs|pinguin|bear|wolf|cat|rat)/, function (req, res) {
    res.send('dogs or pinguin');
});