gpt4 book ai didi

reactjs - 如何将 axios 中的数组参数传递到 Spring Controller ?

转载 作者:行者123 更新时间:2023-12-03 22:11:16 25 4
gpt4 key购买 nike

我正在尝试使用 axios get request 将名称数组传递给 spring Controller 。如果我尝试在 params 中传递单个值,它工作正常,但如果在 params 中传递数组,那么我会收到错误“CORS header ‘Access-Control-Allow-Origin ' 丢失的”。我试过这个

这是网址

http://localhost:8080/onlineshopping/view/category/products?name[]=Alex&name[]=john

taskAction.js
var request = {
params: {
name : JSON.parse(localStorage.getItem('name'))
}
}
const res = await axios.get(`http://localhost:8080/onlineshopping/view/category/products`,request);

dispatch({
type: GET_CATEGORY_PRODUCTS,
payload: res.data
});
};

但这不起作用

我的 Spring Controller
@RequestMapping(value = "/view/category/products")
public Map<String, Object> viewProducts(
@RequestParam(value = "name[]", required = false) List<String> name,
HttpServletRequest request, HttpServletResponse response) {

Map<String, Object> mapproducts = new HashMap<String, Object>();

for (String Str : name) {
System.out.println("name " + Str);
}

最佳答案

您可以使用查询字符串解析和字符串化库“qs”。

import Qs from 'qs'

params = {
name : JSON.parse(localStorage.getItem('name'))
}

let myAxios = axios.create({
paramsSerializer: params => Qs.stringify(params, {arrayFormat: 'repeat'})
})

const res = await
myAxios.get(`http://localhost:8080/onlineshopping/view/category/products`, {params});

dispatch({
type: GET_CATEGORY_PRODUCTS,
payload: res.data
});
};

你会得到这样的网址
http://localhost:8080/onlineshopping/view/category/products?name=Alex&name=john

在 Spring Controller 中,您可以使用拆分字符串
Arrays.asList(name.split("\\s*,\\s*"))

Spring Controller
@RequestMapping(value = "/view/category/products")
public Map<String, Object> viewProducts(
@RequestParam(value = "name", required = false) String name,
HttpServletRequest request, HttpServletResponse response) {

List<String> name = Arrays.asList(name.split("\\s*,\\s*"));

关于reactjs - 如何将 axios 中的数组参数传递到 Spring Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54158331/

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