第三方测试正常的API在本地项目调用返回403及空指针异常问题
解决Axios GET请求传参导致后端NullPointerException的问题
你的代码里Axios GET请求的参数传递方式有误,导致后端接收不到category参数,触发了空指针异常。Postman用Raw JSON能正常工作,是因为你正确设置了请求体,但Axios的GET请求语法和POST不同,这里给你两个可行的修正方案:
方案一:适配后端要求的GET带请求体场景
Axios的GET方法没有单独的data参数,第二个参数是配置对象。如果后端确实要求GET请求携带JSON请求体,需要把参数放在配置的data字段中,同时注意不要嵌套数组:
function filterCategory() { const selectedCategories = Array.from(document.querySelectorAll('.filter-button:checked')).map(checkbox => checkbox.id); showfilterProduct(selectedCategories); } function showfilterProduct(selectedCategories) { axios.get("http://localhost:8080/api/products/filter", { data: { category: selectedCategories // 直接传入生成的数组,避免二次嵌套 }, headers: { "Content-Type": "application/json", "Accept": "*/*", } }) .then(response => { const filterProduct = response.data; console.log(filterProduct); }) .catch(error => { console.log('error', error); }); }
方案二:改用查询参数传递(更符合REST规范)
如果后端支持通过URL查询参数接收分类列表,可以用Axios的params字段传递,它会自动把数组格式化为category=xxx&category=yyy的形式:
function filterCategory() { const selectedCategories = Array.from(document.querySelectorAll('.filter-button:checked')).map(checkbox => checkbox.id); showfilterProduct(selectedCategories); } function showfilterProduct(selectedCategories) { axios.get("http://localhost:8080/api/products/filter", { params: { category: selectedCategories }, headers: { "Content-Type": "application/json", "Accept": "*/*", } }) .then(response => { const filterProduct = response.data; console.log(filterProduct); }) .catch(error => { console.log('error', error); }); }
关键错误点说明
- 原代码把请求参数放在了Axios GET的第二个参数位置,但这个位置是配置对象,不是请求体;
[selectedCategories]会把已有的数组再包一层变成二维数组,后端解析时无法正确映射到FilterDto的category字段,导致criteria对象为空。
内容的提问来源于stack exchange,提问作者C3ddyyy
相关产品推荐
相关产品推荐

