2024-01-21

Process URL in the same way as Express does to get request parameters in a get command

I want to be able to get the parameters from a uri string in the exact same way as Express does. I can do it with regex or other string methods, but then I have a risk that it is not interpretted the same way as Express. I would prefer a way that even if Express has a bug and a URI gets interpretted wrongly, that the function does that as well.

I have Ajax commands that execute a specific get/post command and use the referer to know where they originated eg. req.headers.referer which would be something like http://localhost:3000/data/theme-chalkboard/black

I have a non standard get in Express, for example:

app.get('/data/theme-:theme/:piece', (req, res, next) => {
// server code
}

Where the parameters in question are:

{
  theme: "chalkboard",
  piece: "black"
}

However I have other parts that also have similar incorporated variables within the route. The reason for this is because the route gets dynamically created and updated as the website is used by oneself and others. Because of this, I might need information on one page to be able to query it correctly on another.

From the referer I get a URI string eg.

http://localhost:3000/data/theme-chalkboard/black 
or 
http://localhost:3000/hg-1000

Then I want to be able to first determine which of the following get commands it matches:

app.get('/data/theme-:theme/:piece', (req, res, next) => {});
or 
app.get('/hg-:gameId', (req, res) => {});

And lastly get the parameters in a JSON format, eg.

{
  "theme": "chalkboard",
  "piece": "black"
}

or

{
  "gameId": "1000"
}

If I have to add custom code to first determine each type of command and then to get the parameters as well it is still fine, as this would be similar to the regex idea that I am currently considering. The problems with this solution is that my regex might not always interpret the URI exactly like Express would and I would have to do this for each of the routes that could get a command. I would prefer a generic solution that acomplishes this if it exists.



No comments:

Post a Comment