Setting query string using Fetch GET request

2020-01-24 11:15发布

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?

10条回答
smile是对你的礼貌
2楼-- · 2020-01-24 11:39

A concise ES6 approach:

fetch('https://example.com?' + new URLSearchParams({
    foo: 'value',
    bar: 2,
}))

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.

查看更多
别忘想泡老子
3楼-- · 2020-01-24 11:43

Maybe this is better:

const withQuery = require('with-query');

fetch(withQuery('https://api.github.com/search/repositories', {
  q: 'query',
  sort: 'stars',
  order: 'asc',
}))
.then(res => res.json())
.then((json) => {
  console.info(json);
})
.catch((err) => {
  console.error(err);
});
查看更多
Viruses.
4楼-- · 2020-01-24 11:45

You can use #stringify from query string

import { stringify } from 'query-string';

fetch(`https://example.org?${stringify(params)}`)
查看更多
相关推荐>>
5楼-- · 2020-01-24 11:46

encodeQueryString — encode an object as querystring parameters

/**
 * Encode an object as url query string parameters
 * - includes the leading "?" prefix
 * - example input — {key: "value", alpha: "beta"}
 * - example output — output "?key=value&alpha=beta"
 * - returns empty string when given an empty object
 */
function encodeQueryString(params) {
    const keys = Object.keys(params)
    return keys.length
        ? "?" + keys
            .map(key => encodeURIComponent(key)
                + "=" + encodeURIComponent(params[key]))
            .join("&")
        : ""
}

encodeQueryString({key: "value", alpha: "beta"})
 //> "?key=value&alpha=beta"
查看更多
ら.Afraid
6楼-- · 2020-01-24 11:46

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}):

function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) {
    if(query) {
        fetchLink += '?';
        let count = 0;
        const queryLength = Object.keys(query).length;
        for(let key in query) {
            fetchLink += key+'='+query[key];
            fetchLink += (count < queryLength) ? '&' : '';
            count++;
        }
    }
    // link becomes: 'http://myapi.com/orders?order_id=1'
    // Then, use fetch as in MDN and simply pass this fetchLink as the url.
}

I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.

查看更多
地球回转人心会变
7楼-- · 2020-01-24 11:47

Template literals are also a valid option here, and provide a few benefits.

You can include raw strings, numbers, boolean values, etc:

    let request = new Request(`https://example.com/?name=${'Patrick'}&number=${1}`);

You can include variables:

    let request = new Request(`https://example.com/?name=${nameParam}`);

You can include logic and functions:

    let request = new Request(`https://example.com/?name=${nameParam !== undefined ? nameParam : getDefaultName() }`);

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:

let queryString = [
  `param1=${getParam(1)}`,
  `param2=${getParam(2)}`,
  `param3=${getParam(3)}`,
].join('&');

let request = new Request(`https://example.com/?${queryString}`, {
  method: 'GET'
});
查看更多
登录 后发表回答