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