gpt4 book ai didi

javascript - Axios 参数中存在多个值(逗号分隔)

转载 作者:行者123 更新时间:2023-11-28 14:28:12 27 4
gpt4 key购买 nike

预期的查询字符串:

http://fqdn/page?categoryID=1&categoryID=2

axios获取请求:

fetchNumbers () {
return axios.get(globalConfig.CATS_URL, {
params: {
...(this.category ? { categoryId: this.category } : {})
}
})
.then((resp) => {
// console.log(resp)
})
.catch((err) => {
console.log(err)
})
}

如您所见,它只需 1 个参数的 1 个值即可完美工作,但如果我想创建多个值 - 它不起作用,我尝试使用数组:

...(this.category ? { categoryId: [1, 2] } : {})

但它以这种方式返回:

http://fqdn/page?categoryID[]=1&categoryID[]=2

所以它不起作用。看看这个问题:Passing an object with a parameter with multiple values as a query string in a GET using axios

但不知道他是如何解决这个问题的。

最佳答案

您可以使用axios的paramsSerializer自定义请求中参数的序列化。

请注意URLSearchParams按照您期望的方式序列化数组数据:

const searchParams = new URLSearchParams();
searchParams.append('foo', 1);
searchParams.append('foo', 2);
console.log(searchParams.toString()); // foo=1&foo=2

因此您可以在 paramsSerializer 中使用该类,如下所示:

// my-axios.js
export default axios.create({
paramsSerializer(params) {
const searchParams = new URLSearchParams();
for (const key of Object.keys(params)) {
const param = params[key];
if (Array.isArray(param)) {
for (const p of param) {
searchParams.append(key, p);
}
} else {
searchParams.append(key, param);
}
}
return searchParams.toString();
}
});

// Foo.vue
import axios from './my-axios.js';

export default {
methods: {
async send() {
const { data } = await axios({
url: '//httpbin.org/get',
params: {
categoryId: [1, 2, 3]
}
});

// ...
}
}
}

demo

关于javascript - Axios 参数中存在多个值(逗号分隔),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52482203/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com