To send GET query parameters with Javascript fetch, simply create a new URL object and append the search parameters: var data = { "KEY" : "VALUE" }; var url = new URL("http://site.com/API"); for (let k in data) { url.
Here is an example where query is passed as a json object (query = {order_id: 1}): function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) { if(query) { fetchLink += '? '; let count = 0; const queryLength = Object. keys(query).
The fetch() method: Fetch API comes with a fetch () method that allows you to fetch data from all sorts of different places and work with the data fetched. It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data).
While query parameters are typically used in GET requests, it's still possible to see them in POST and DELETE requests, among others. Your query parameters can be retrieved from the query object on the request object sent to your route.
Update March 2017:
URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.
The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
However, I'm not sure Chrome supports the searchParams
property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.
Update April 2018:
With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search
instead of looping over all keys and append them
var url = new URL('https://sl.se')
var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]
url.search = new URLSearchParams(params).toString();
fetch(url)
Sidenote: URLSearchParams
is also available in NodeJS
const { URL, URLSearchParams } = require('url');
A concise, modern approach:
fetch('https://example.com?' + new URLSearchParams({
foo: 'value',
bar: 2,
}))
URLSearchParams's toString() function will convert the provided query args into a string. In JavaScript, when you concatenate an object with a string, that object's toString() function will automatically be called for you. You may prefer to be more explicit about what's happening here, and choose to call .toString() yourself before concatenating the two values together, like this: fetch('https://...' + new URLSearchParams(...).toString())
IE does not support URLSearchParams (or fetch), but there are polyfills available.
If using node, you can add the fetch API through a package like node-fetch. URLSearchParams comes with node, and can be found as a global object since version 10. In older version you can find it at require('url').URLSearchParams
.
If you're using node and typescript together, you'll find that, due to some technical limitations, typescript does not offer type definitions for the global URLSearchParams. The simplist workaround is to just import it from the URL module. See here for more info.
let params = {
"param1": "value1",
"param2": "value2"
};
let query = Object.keys(params)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
.join('&');
let url = 'https://example.com/search?' + query;
fetch(url)
.then(data => data.text())
.then((text) => {
console.log('request succeeded with JSON response', text)
}).catch(function (error) {
console.log('request failed', error)
});
As already answered, this is per spec not possible with the fetch
-API, yet. But I have to note:
If you are on node
, there's the querystring
package. It can stringify/parse objects/querystrings:
var querystring = require('querystring')
var data = { key: 'value' }
querystring.stringify(data) // => 'key=value'
...then just append it to the url to request.
However, the problem with the above is, that you always have to prepend a question mark (?
). So, another way is to use the parse
method from nodes url
package and do it as follows:
var url = require('url')
var data = { key: 'value' }
url.format({ query: data }) // => '?key=value'
See query
at https://nodejs.org/api/url.html#url_url_format_urlobj
This is possible, as it does internally just this:
search = obj.search || (
obj.query && ('?' + (
typeof(obj.query) === 'object' ?
querystring.stringify(obj.query) :
String(obj.query)
))
) || ''
You can use #stringify
from query string
import { stringify } from 'query-string';
fetch(`https://example.org?${stringify(params)}`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With