You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用axios向后端GET接口传参请求优惠券返回400错误如何解决

问题原因
  • 后端接口参数注解使用错误:你接口路径定义的是@GetMapping("coupon/{price}"),属于路径参数,但参数上用了@RequestParam(该注解仅用来接收?price=xxx形式的查询参数),前后参数匹配逻辑不一致,导致后端识别不到传入的价格参数,返回400错误。
  • 前端URL拼接存在隐患:如果globals.urls.customerCouponsByPrice末尾没有自带斜杠,直接拼接数字会生成类似/coupon1000的错误路径,同样会触发400/404错误。
修复方案

你可以二选其一调整代码:

方案1:后端保留路径参数定义(和你当前写的路径规则匹配)

修改后端代码,把参数注解换成接收路径参数的@PathVariable:

@GetMapping("coupon/{price}")
@ResponseStatus(HttpStatus.ACCEPTED)
public List<Coupon> getCustomerCouponsByMaxPrice(@PathVariable double price) {
    return customerService.getCustomerCouponsByMaxPrice(price);
}

前端调整请求写法,保证URL拼接格式正确:

// 用模板字符串主动补全斜杠,避免拼接出错
const response = await axios.get<CouponModel[]>(`${globals.urls.customerCouponsByPrice}/${1000}`);
// 最终生成的请求URL符合预期:http://localhost:8080/api/customer/coupon/1000

方案2:后端改用查询参数接收

如果你想保留@RequestParam注解,就调整后端路径定义,去掉路径里的占位符:

@GetMapping("coupon")
@ResponseStatus(HttpStatus.ACCEPTED)
public List<Coupon> getCustomerCouponsByMaxPrice(@RequestParam double price) {
    return customerService.getCustomerCouponsByMaxPrice(price);
}

前端通过axios的params配置项传参即可:

const response = await axios.get<CouponModel[]>(globals.urls.customerCouponsByPrice, {
  params: {
    price: 1000
  }
});
// 最终生成的请求URL:http://localhost:8080/api/customer/coupon?price=1000

内容的提问来源于stack exchange,提问作者Fastaca Girasol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:45:04