My project is using local server proxy. It proxys an api to my local file path by using regex.
Here is my scene:
My local http request is '/api/bpm/fetch-action-progress-bar?bpm=123' and it will finally find the json file name of 'app/data/bpm/fetch-action-progress-bar.json'.
Precondition: only the path begins with '/api' should be rewritten And the api path is uncertain.
Realizing a 'myRegex' to satisfy the three examples below:
example 1
'/api/bpm/fetch-action-progress-bar?bpm=123'.replace(myRegex, 'app/data/$1.json')
wanted: 'app/data/bpm/fetch-action-progress-bar.json'
example 2
'/api/bpm/fetch-action-progress-bar'.replace(myRegex, 'app/data/$1.json')
wanted: 'app/data/bpm/fetch-action-progress-bar.json'
example 3
'/api/yt/order/export?id=1212'.replace(myRegex, 'app/data/$1.json')
wanted: 'app/data/yt/order/export.json'
I can only use replace method, help me to realize a 'myRegex' to solve it. My difficulty is the query parameters may not existing.
/.*?(?!.*\/)([\w\-]+)[^?]?.*/
Made the queryparam '?' optional.
I checked this in jsfiddle.net
console.log('/api/bpm/fetch-action-progress-bar?bpm=123'.replace(/.*?(?!.*\/)([\w\-]+)[^?]?.*/, 'app/data/$1.json'))
console.log('/api/bpm/fetch-action-progress-bar'.replace(/.*?(?!.*\/)([\w\-]+)[^?]?.*/, 'app/data/$1.json'))
Demo and explanation here: https://regex101.com/r/HBvG3K/10 regex101.com/r/HBvG3K/11
Updated as per the request in the chat
\/api\/([\w\-\/]+).*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With