Reputation: 59
I'm working on a project and i want to define url object that will be passed to fetch ex. https://t1.testing.com/test/api/v1/blog?pagingindex=0&pagingresults=10
const url_object = {
url: `https://t1.testing.com/test/api/v1/blog`,
url_params: {
method: "POST",
pagingindex: 0,
pagingresults: 10
}
};
and when i call fetch(url_object.url, url_object.url_params)
i get an error. How can i incorporate this into fetch? So i need to allow user to define method and query string that will be passed. Thanks in advance!
Upvotes: 3
Views: 10482
Reputation: 8122
You can have your cake and eat it too -- easily convert dictionary style objects to query parameters with no fuss:
var url = new URL('https://example.com/');
url.search = new URLSearchParams({blah: 'lalala', rawr: 'arwrar'});
console.log(url.toString()); // https://example.com/?blah=lalala&rawr=arwrar
Upvotes: 3
Reputation: 943097
The object you have labeled url_params
is described by the MDN documentation as:
An options object containing any custom settings that you want to apply to the request.
It then goes on to list the properties you can include there.
pagingindex
and pagingresults
are not among them.
The query string is part of the URL. If you want to put data there, then put it in the URL.
const url_object = {
url: `https://t1.testing.com/test/api/v1/blog?pagingindex=0&pagingresults=10`,
url_params: {
method: "POST"
}
};
You may wish to use the URL object to construct the URL (it will handle escaping for you).
Upvotes: 1