admin管理员组

文章数量:1399006

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!

Share Improve this question edited May 29, 2018 at 16:01 Get Off My Lawn 36.4k46 gold badges198 silver badges375 bronze badges asked May 29, 2018 at 15:56 JackyJacky 591 gold badge3 silver badges9 bronze badges 3
  • 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
Add a ment  | 

2 Answers 2

Reset to default 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./');
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).

本文标签: Query string with fetch javascriptStack Overflow