'app.get or router.get post, delete, patch etc., failing when sending an http request as a URL parameter or variable

I just wasted a lot of time trying to send an url in a fetch from a React app to a nodejs server. The server would not detect the request at all, even though the route was correct! I was very frustrated. Then I realized that if I sent anything else other than the url, the route actually worked and responded correctly, so why was the route becoming muddled by me including a url either as a parameter, as a variable or even if I included it inside an object property?

the raw string was an url address to an image:

const string = 'https:://zzz.io/yyyyy/products/image.jpg'

fetch(`https://xxxx.io/yyyyyy/products/{"isId":false,"identification":"${string}"}`, requestOptions)

the route wouldn't be hit at the server and a not found error would be reported.

I tried using:

const string = encodeURIComponent('https:://zzz.io/yyyyy/products/image.jpg')

, and curiously react would add the last url that had been used by the app to the string, messing the intended url completely.



Solution 1:[1]

The answer lied in the root cause of the problem, I had to rediscover the powder... The forward slash was messing everything up and I probable discovered what for many of you was obvious to start with, you can have a / anywhere in the fetch call other than in the main url you are fetching. Once I understood this, then the solutions became obvious:

Solution 1: you can remove the slash and re-insert it in the server and everything would work.

Or

Best Solution:

simply replace the forward slash in your client API string with %2F and then call fetch and the nodejs server app and/route will be happy and work like a charm. Very simple to do and no need to use functions like encodeURIComponent, that in my case only added confusion. Just do:

string.replace(/\//g, "%2F")

and then fetch as in the question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Julio Spinelli