Javascript 使用 Fetch GET 请求设置查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35038857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting query string using Fetch GET request
提问by mylescc
I'm trying to use the new Fetch API:
我正在尝试使用新的Fetch API:
I am making a GET
request like this:
我正在提出这样的GET
请求:
var request = new Request({
url: 'http://myapi.com/orders',
method: 'GET'
});
fetch(request);
However, I'm unsure how to add a query string to the GET
request. Ideally, I want to be able to make a GET
request to a URL
like:
但是,我不确定如何向GET
请求添加查询字符串。理想情况下,我希望能够向喜欢的人GET
提出请求URL
:
'http://myapi.com/orders?order_id=1'
In jQuery
I could do this by passing {order_id: 1}
as the data
parameter of $.ajax()
. Is there an equivalent way to do that with the new Fetch API
?
在jQuery
我可以通过做这个{order_id: 1}
作为data
参数$.ajax()
。有没有等效的方法来使用 new 来做到这一点Fetch API
?
回答by CodingIntrigue
Update March 2017:
2017 年 3 月更新:
URL.searchParamssupport has officially landed in Chrome 51, but other browsers still require a polyfill.
URL.searchParams支持已正式登陆 Chrome 51,但其他浏览器仍然需要polyfill。
The officialway to work with query parameters is just to add them onto the URL. From the spec, this is an example:
使用查询参数的官方方法是将它们添加到 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(/* … */)
However, I'm not sure Chrome supports the searchParams
property of a URL (at the time of writing) so you might want to either use a third party libraryor roll-your-own solution.
但是,我不确定 Chrome 是否支持searchParams
URL的属性(在撰写本文时),因此您可能想要使用第三方库或推出自己的解决方案。
Update April 2018:
2018 年 4 月更新:
With the use of URLSearchParams constructoryou could assign a 2D array or a object and just assign that to the url.search
instead of looping over all keys and append them
通过使用URLSearchParams 构造函数,您可以分配一个 2D 数组或一个对象,并将其分配给url.search
而不是循环遍历所有键并附加它们
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)
Sidenote: URLSearchParams
is also available in NodeJS
旁注:URLSearchParams
在 NodeJS 中也可用
const { URL, URLSearchParams } = require('url');
回答by Sudharshan
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)
});
回答by yckart
As already answered, this is per spec not possible with the fetch
-API, yet. But I have to note:
正如已经回答的那样,这对于fetch
-API 来说是不可能的,但是。但我必须注意:
If you are on node
, there's the querystring
package. It can stringify/parse objects/querystrings:
如果你在node
,有querystring
包裹。它可以字符串化/解析对象/查询字符串:
var querystring = require('querystring')
var data = { key: 'value' }
querystring.stringify(data) // => 'key=value'
...then just append it to the url to request.
...然后只需将其附加到要请求的 url。
However, the problem with the above is, that you always have to prepend a question mark (?
). So, another way is to use the parse
method from nodes url
package and do it as follows:
然而,上面的问题是,你总是必须在前面加上一个问号 ( ?
)。因此,另一种方法是使用parse
节点url
包中的方法并按如下方式执行:
var url = require('url')
var data = { key: 'value' }
url.format({ query: data }) // => '?key=value'
See query
at https://nodejs.org/api/url.html#url_url_format_urlobj
见query
在https://nodejs.org/api/url.html#url_url_format_urlobj
This is possible, as it does internally just this:
这是可能的,因为它在内部只是这样:
search = obj.search || (
obj.query && ('?' + (
typeof(obj.query) === 'object' ?
querystring.stringify(obj.query) :
String(obj.query)
))
) || ''
回答by Scotty Jamison
A concise ES6 approach:
一个简洁的 ES6 方法:
fetch('https://example.com?' + new URLSearchParams({
foo: 'value',
bar: 2,
}))
URLSearchParam'stoString() function will convert the query args into a string that can be appended onto the URL. In this example, toString() is called implicitly when it gets concatenated with the URL.
URLSearchParam 的toString() 函数会将查询参数转换为可以附加到 URL 的字符串。在此示例中,当与 URL 连接时,会隐式调用 toString()。
IE does not support this feature, but there are polyfillsavailable.
IE 不支持此功能,但有可用的polyfill。
回答by Hirurg103
You can use #stringify
from query string
您可以使用#stringify
from查询字符串
import { stringify } from 'query-string';
fetch(`https://example.org?${stringify(params)}`)
回答by ChaseMoskal
encodeQueryString — encode an object as querystring parameters
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"
回答by Bin HOU
Maybe this is better:
也许这更好:
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);
});
回答by Evert
I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:
我知道这是绝对显而易见的,但我觉得值得添加这个作为答案,因为它是最简单的:
var orderId = 1;
var request = new Request({
url: 'http://myapi.com/orders?order_id=' + orderId,
method: 'GET'
});
fetch(request);
回答by Pat Kearns
Template literals are also a valid option here, and provide a few benefits.
模板文字在这里也是一个有效的选择,并提供一些好处。
You can include raw strings, numbers, boolean values, etc:
您可以包含原始字符串、数字、布尔值等:
let request = new Request(`https://example.com/?name=${'Patrick'}&number=`);
You can include variables:
您可以包含变量:
let request = new Request(`https://example.com/?name=${nameParam}`);
You can include logic and functions:
您可以包含逻辑和函数:
let request = new Request(`https://example.com/?name=${nameParam !== undefined ? nameParam : getDefaultName() }`);
As far as structuring the data of a larger query string, I like using an array concatenated to a string. I find it easier to understand than some of the other methods:
至于构造更大的查询字符串的数据,我喜欢使用连接到字符串的数组。我发现它比其他一些方法更容易理解:
let queryString = [
`param1=${getParam(1)}`,
`param2=${getParam(2)}`,
`param3=${getParam(3)}`,
].join('&');
let request = new Request(`https://example.com/?${queryString}`, {
method: 'GET'
});
回答by Amjad Abujamous
Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):
刚刚使用 Nativescript 的 fetchModule 并使用字符串操作找出了我自己的解决方案。将查询字符串一点一点地附加到 url 中。这是一个将查询作为 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.
}
I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.
我通过多个查询参数对此进行了测试,它的工作原理非常棒:) 希望这对某人有所帮助。