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


当前回答

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

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

其他回答

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

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

import { stringify } from 'query-string';

fetch(`https://example.org?${stringify(params)}`)
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)
  });

没有外部包的解决方案

使用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

也许这样更好:

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