I'm with a tricky problem here. I have created an API that will fetch some data from an external API. For example:
I have this endpoint on my current api:
/api/items?q=
And on the route responsible for that, I have this code:
itemsRouter.get("/", async (req, res) => {
const { q } = req.query;
try {
const url = new URL(`externalapiurl?q=${q}`);
console.log(url);
});
} catch (error) {
logger.error(error);
}
});
However, if I check my url with console.log
, the url is always being printed with a espaço encoded, something like: /search?q=%E2%80%8Biphone'
If I check the url object from new URL
on my node terminal, I can see a little space at my q key:
{ 'q' => ' iphone' }
The url object print is bellow:
href:
'externalapiurl?q=%E2%80%8Bapple%20iphone',
origin: 'externalapiurl',
protocol: 'https:',
username: '',
password: '',
host: 'externalapiurl',
hostname: 'externalapiurl',
port: '',
pathname: 'externalapiurl',
search: '?q=%E2%80%8Bapple%20iphone',
searchParams: URLSearchParams { 'q' => ' iphone' },
hash: '' }
Because of that, the request isn't being made correctly. I have already tried encodeURI nd encodeURIComponent, however the problem persist.
PS: This new URL comes from const URL = require("url").URL;
And I'm using node-fetch
to handle the url call.
Any help will be appreciated! Thanks.