Home > Enterprise >  ExpressJs regex in routing
ExpressJs regex in routing

Time:09-09

I am currently trying to create a calculator API using ExpressJs. My problem is using regex as routes to determine common patterns.

A valid typical route is api/calculator/:operator/:number1/:number2 where by operator is a mathematical operator in a string format (add, subtract, multiply, divide) and number1 and number2 are operands.

My aim is, if any number is missed in the route, e.g api/calculator/:operator/:number1/, or api/calculator/:operator//:number2 or api/calculator/:operator// I want to send a response that the operands are invalid.

Also, if the operator is not valid, a response needs to be sent as a well.

How can I use regex to determine if the route is a valid one?

CodePudding user response:

In your routing you can use a regex to require at least one char in each of the three params:

app.get('api/calculator/:operator(.{1,})/:number1(.{1,})/:number2(.{1,})', (req, res) => { ... });
app.get('api/calculator/*', (req, res) => { ... });

The first routing is used for valid patterns, the second routing is used for error reporting

You can also apply a pattern to further restrict the routing, such as alpha only for the operator, and numbers only for the numbers:

app.get('api/calculator/:operator([A-Za-z] )/:number1([ -]?[0-9.] )/:number2([ -]?[0-9.] )', (req, res) => { ... });

Or, go for more fancy number validation with ([ -]?[0-9] (\\.[0-9] )?)

CodePudding user response:

First Wow this is Just Wrong

My aim is, if any number is missed in the route, e.g api/calculator/:operator/:number1/, or api/calculator/:operator//:number2 or api/calculator/:operator// I want to send a response that the operands are invalid.

If the route is defined you can't interchange them

The thing with express routes is that its Relative in nature so if a GET Route Such as this is called api/calculator/:operator/:number1/:number2 as api/calculator/*/3/3

the operator would be " " and number1 would be "3" and number2 would be "3" but in a GET Route api/calculator/*/3 or api/calculator/*

the operator would be " " and number1 would be "3" and number2 would be "undefined"

The correct way is to handle it as Express Query

So your code should be like api/calculator/?operator=" "&number1="3"&number2="3"

So this way you can access the query and the application won't crash when interchange using req.query.value

https://expressjs.com/en/api.html#req.query to read more

  • Related