我正在尝试使用新的Fetch API:

我像这样做一个GET请求:

var request = new Request({
  url: 'http://myapi.com/orders',
  method: 'GET'
});
fetch(request);

但是,我不确定如何向GET请求添加查询字符串。理想情况下,我希望能够做出一个GET请求到一个URL像:

'http://myapi.com/orders?order_id=1'

在jQuery中,我可以通过传递{order_id: 1}作为$.ajax()的数据参数来做到这一点。在新的Fetch API中,是否有等效的方法来做到这一点?


当前回答

encodeQueryString -将对象编码为查询字符串参数

/**
 * 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"

其他回答

你可以从query-string中使用stringify。

import { stringify } from 'query-string';

fetch(`https://example.org?${stringify(params)}`)

刚刚与Nativescript的fetchModule一起工作,并使用字符串操作找出了我自己的解决方案。 将查询字符串逐位附加到url。下面是一个示例,query作为json对象传递(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.
}

我测试了多个查询参数,它像一个魅力:) 希望这能帮助到一些人。

简洁、现代的方法:

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

它是如何工作的:当一个字符串(例如URL)与URLSearchParams的实例连接时,它的toString()方法将自动被调用,以将实例转换为字符串表示,这恰好是一个正确编码的查询字符串。如果自动调用toString()对您来说太神奇了,您可能更喜欢像这样显式地调用它:' + new URLSearchParams(…).toString())

一个带查询参数的获取请求的完整示例:

//你可以复制粘贴的例子。 // jsonplaceholder.typicode.com提供了一个虚拟的rest-api //为了这个目的。 异步函数doAsyncTask() { url = ( “https://jsonplaceholder.typicode.com/comments?”+ new URLSearchParams({postId: 1}).toString() ); Const result = await fetch(url) .then(response => response.json()); console.log(' fetch from: ' + url); console.log(结果); } doAsyncTask ();


如果您正在使用/支持……

IE: Internet Explorer does not provide native support for URLSearchParams or fetch, but there are polyfills available. Node: As of Node 18 there is native support for the fetch API (in version 17.5 it was behind the --experimental-fetch flag). In older versions, 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. Node + TypeScript: 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 simplest workaround is to just import it from the url module. See here for more info.

也许这样更好:

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

我知道这是非常明显的陈述,但我觉得有必要加上这个作为答案,因为它是所有答案中最简单的:

const orderId = 1;
fetch('http://myapi.com/orders?order_id=' + orderId);