我正在尝试使用新的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中,是否有等效的方法来做到这一点?


2017年3月更新:

URL。searchParams支持已正式登陆Chrome 51,但其他浏览器仍然需要polyfill。


使用查询参数的正式方法是将它们添加到URL上。下面是一个例子:

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(/* … */)

然而,我不确定Chrome是否支持URL的searchParams属性(在编写时),所以你可能想要使用第三方库或滚动自己的解决方案。

2018年4月更新:

使用URLSearchParams构造函数,您可以分配一个2D数组或对象,并将其分配给url。搜索而不是遍历所有键并附加它们

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)

注:URLSearchParams在NodeJS中也可用

const { URL, URLSearchParams } = require('url');

正如前面所回答的,这在fetch-API中是不可能实现的。但我必须指出:

如果你在node上,有querystring包。它可以stringify/解析对象/查询字符串:

var querystring = require('querystring')
var data = { key: 'value' }
querystring.stringify(data) // => 'key=value'

...然后把它附加到url请求。


然而,上面的问题是,您总是必须在前面加上一个问号(?)。所以,另一种方法是使用解析方法从节点url包,并做如下:

var url = require('url')
var data = { key: 'value' }
url.format({ query: data }) // => '?key=value'

参见https://nodejs.org/api/url.html#url_url_format_urlobj查询

这是可能的,因为它内部是这样做的:

search = obj.search || (
    obj.query && ('?' + (
        typeof(obj.query) === 'object' ?
        querystring.stringify(obj.query) :
        String(obj.query)
    ))
) || ''
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)
  });

也许这样更好:

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

模板文字在这里也是一个有效的选项,并提供了一些好处。

你可以包括原始字符串,数字,布尔值等:

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

你可以包含变量:

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

你可以包括逻辑和函数:

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

至于构造较大查询字符串的数据,我喜欢使用连接到字符串的数组。我发现它比其他一些方法更容易理解:

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

let request = new Request(`https://example.com/?${queryString}`, {
  method: 'GET'
});

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

简洁、现代的方法:

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.

刚刚与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.
}

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

var paramsdate=01+'%s'+12+'%s'+2012+'%s';

request.get(“https://www.exampleurl.com?fromDate=”+paramsDate;

没有外部包的解决方案

使用fetch api执行GET请求,我在这个解决方案中工作,不需要安装包。

这是一个调用谷歌的映射API的例子

// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = { 
    key: "asdkfñlaskdGE",
    address: "evergreen avenue",
    city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()

请随意复制这段代码并将其粘贴到控制台上,看看它是如何工作的!!

生成的url是这样的:

https://maps.googleapis.com/maps/api/geocode/json?key=asdkf%C3%B1laskdGE&address=evergreen%20avenue&city=New%20York

这是我在决定写这篇文章之前所看到的,喜欢:D