查询参数中具有相同键的多个字段(axios 请求)? [英] Multiple fields with same key in query params (axios request)?
问题描述
所以后端(不在我的控制之下)需要一个这样的查询字符串:
http://example.com/?foo=5&foo=2&foo=11
但是axios
使用JS对象发送请求参数:
axios.get('http://example.com/', { foo: 5 });
很明显,这样的对象不能有多个具有相同键的字段.
如何使用相同的键发送包含多个字段的请求?
<块引用>
来自 请求配置
上的 axios 文档//`params` 是与请求一起发送的 URL 参数//必须是普通对象或 URLSearchParams 对象参数:{编号:12345},
要在请求中使用它,你会这样做
var request = {参数:{foo: [5, 2, 11]}}axios.get('http://example.com/', request);
使用普通对象方法的唯一问题是数组参数添加为
http://example.com/?foo[]=5&foo[]=2&foo[]=11
要获得没有 []
的请求,您可以使用 URLSearchParams
var params = new URLSearchParams();params.append("foo", 5);params.append("foo", 2);params.append("foo", 11);无功请求 = {参数:参数};axios.get('http://example.com/', request);
这将导致请求为
http://example.com/?foo=5&foo=2&foo=11
So the backend (not under my control) requires a query string like this:
http://example.com/?foo=5&foo=2&foo=11
But axios
uses JS object to send the request params:
axios.get('http://example.com/', { foo: 5 });
And obviously such object can't have multiple fields with the same key.
How can I send a request with multiple fields with same key?
From the axios documentation on the request config
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
},
To use this in a request, you would do
var request = {
params: {
foo: [5, 2, 11]
}
}
axios.get('http://example.com/', request);
The only issue with using a plain object approach is that array parameters are added as
http://example.com/?foo[]=5&foo[]=2&foo[]=11
To get request without the []
like you want, you can use the URLSearchParams
var params = new URLSearchParams();
params.append("foo", 5);
params.append("foo", 2);
params.append("foo", 11);
var request = {
params: params
};
axios.get('http://example.com/', request);
This will result in a request as
http://example.com/?foo=5&foo=2&foo=11
这篇关于查询参数中具有相同键的多个字段(axios 请求)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!