I'm working on a project and i want to define url object that will be passed to fetch ex. ;pagingresults=10
const url_object = {
url: ``,
url_params: {
method: "POST",
pagingindex: 0,
pagingresults: 10
}
};
I'm working on a project and i want to define url object that will be passed to fetch ex. https://t1.testing./test/api/v1/blog?pagingindex=0&pagingresults=10
const url_object = {
url: `https://t1.testing./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!
- 5 What is the error? – Get Off My Lawn Commented May 29, 2018 at 15:57
-
Have you tried just passing that same URL to
fetch
as the URL argument? BTW,fetch
does not allow for properties in its initialization object other than those documented, and it takes two arguments: the URL, then the initialization object. – Heretic Monkey Commented May 29, 2018 at 16:00 - Possible duplicate of Setting query string using Fetch GET request – Heretic Monkey Commented May 29, 2018 at 16:07
2 Answers
Reset to default 3You 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./');
url.search = new URLSearchParams({blah: 'lalala', rawr: 'arwrar'});
console.log(url.toString()); // https://example./?blah=lalala&rawr=arwrar
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./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).