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

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

that´s exactly what I stopped doing because I don´t know the domain. yeah I know is dumb
You can get it using localtion.hostname.
@handsome I've edited my answer to include an example using URLSearchParams. You can use a relative URL with this solution.
Now you always have a ugly question mark at the end of the route if params is empty. Is there it bettery way to add the params without something like searchParams.size ? '?' + searchParams.toString() : ''?
@YannickSchröder Yes, you can create a URL object, modify its searchParams and then use `/api/cars${url.search}`, here is an example
|
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]))
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.