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 callfetch(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!
- 5What is the error?Get Off My Lawn– Get Off My Lawn2018-05-29 15:57:53 +00:00CommentedMay 29, 2018 at 15:57
- Have you tried just passing that same URL to
fetchas the URL argument? BTW,fetchdoes 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– Heretic Monkey2018-05-29 16:00:23 +00:00CommentedMay 29, 2018 at 16:00 - Possible duplicate ofSetting query string using Fetch GET requestHeretic Monkey– Heretic Monkey2018-05-29 16:07:15 +00:00CommentedMay 29, 2018 at 16:07
2 Answers2
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=arwrarThe object you have labeledurl_params is described by theMDN 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 andpagingresults are not among them.
The query string is part of the URL. If you want to put data there, then put itin 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 usethe URL object to construct the URL (it will handle escaping for you).
2 Comments
fetch should befetch(url_object.url, url_object.url_params) if that object is to be used correctly. I know that wasn't part of the question, but for future readers who may not know how the OP was using that might pass that object verbatim tofetch and wonder why it doesn't work.Explore related questions
See similar questions with these tags.
