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


当前回答

没有外部包的解决方案

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

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

你可以从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.