handsome
handsome

Reputation: 2422

Add params to url with javascript

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

Upvotes: 0

Views: 821

Answers (2)

Titus
Titus

Reputation: 22484

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);

Upvotes: 1

Addis
Addis

Reputation: 2530

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]))
})

Upvotes: 0

Related Questions