3

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!

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
Jacky
  • 59
  • 3
  • 9
  • 5
    What is the error? – Get Off My Lawn May 29 '18 at 15:57
  • Have you tried just passing that same URL to `fetch` as the URL argument? BTW, [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/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 May 29 '18 at 16:00
  • Possible duplicate of [Setting query string using Fetch GET request](https://stackoverflow.com/questions/35038857/setting-query-string-using-fetch-get-request) – Heretic Monkey May 29 '18 at 16:07

2 Answers2

3

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
jfunk
  • 7,176
  • 4
  • 37
  • 38
1

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    To be clear, the call to `fetch` should be `fetch(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 to `fetch` and wonder why it doesn't work. – Heretic Monkey May 29 '18 at 16:04
  • Yea i know that, when i pass it like you did it wokrs fine, but i dont want to hardcode it like that because it will need to be dynamic. I will try it with URL object. – Jacky May 29 '18 at 16:30