I'm trying to use the new Fetch API:
I am making a GET
request like this:
var request = new Request({
url: 'http://myapi.com/orders',
method: 'GET'
});
fetch(request);
However, I'm unsure how to add a query string to the GET
request. Ideally, I want to be able to make a GET
request to a URL
like:
'http://myapi.com/orders?order_id=1'
In jQuery
I could do this by passing {order_id: 1}
as the data
parameter of $.ajax()
. Is there an equivalent way to do that with the new Fetch API
?
A concise ES6 approach:
URLSearchParam's toString() function will convert the query args into a string that can be appended onto the URL. In this example, toString() is called implicitly when it gets concatenated with the URL.
IE does not support this feature, but there are polyfills available.
Maybe this is better:
You can use
#stringify
from query stringencodeQueryString — encode an object as querystring parameters
Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):
I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.
Template literals are also a valid option here, and provide a few benefits.
You can include raw strings, numbers, boolean values, etc:
You can include variables:
You can include logic and functions:
As far as structuring the data of a larger query string, I like using an array concatenated to a string. I find it easier to understand than some of the other methods: