0

hello I want to add some params to a url

let params = {doors: 4, color: red}
let request = new Request('/api/cars')
Object.keys(params).forEach(key => request.searchParams.append(key, params[key]))

but I´m getting the Cannot read property 'append' of undefined error

it works if I do

var url = new URL('https://example.com/api/cars');
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
let request = new Request(url)

but since I´m not using URL only relative urls I´m wondering if is not possible to append params to Request

handsome
  • 2,335
  • 7
  • 45
  • 73
  • check it out this issue, https://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript i hope this can help. – Mauricio Feb 11 '20 at 22:37
  • Does this answer your question? [Adding a parameter to the URL with JavaScript](https://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript) – Maksym Bezruchko Feb 11 '20 at 22:41

2 Answers2

1

You can use a URLSearchParams object and append it to the URL string. Here is an example:

const params = {
  doors: 4,
  color: 'red'
};
const searchParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => searchParams.append(key, value));

const request = new Request(`/api/cars?${searchParams.toString()}`);
console.log(request.url);
Titus
  • 22,031
  • 1
  • 23
  • 33
0

The Request() constructor creates a new Request object. So you should use it asynchronously with fetch:

let params = {doors: 4, color: red};
let request = new Request('/api/cars');

fetch(request).then(function(response) {
  Object.keys(params).forEach(key => response.searchParams.append(key, params[key]))
})
Addis
  • 2,480
  • 2
  • 13
  • 21