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

Spring Boot与React项目出现MissingPathVariableException问题求助

问题原因

错误org.springframework.web.bind.MissingPathVariableException: Required URI template variable 'userId' for method parameter type Long is not present的核心原因是:后端接口的路径变量名与@PathVariable注解绑定的参数名不匹配。

具体细节:

  • @GetMapping定义的路径是/expense/{id},路径变量名为id
  • 方法参数上的@PathVariable Long userId未指定对应路径变量名,Spring默认会寻找名为userId的路径变量,两者不匹配导致异常
解决方案

两种修改方式任选其一即可:

方式一:指定@PathVariable对应路径变量名

修改后端ExpenseController的getExpense方法,在@PathVariable注解中明确绑定路径变量id:

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class ExpenseController {
    @Autowired
    ExpenseRepository expenseRepository;
    @GetMapping("/expense/{id}")
    public ResponseEntity<?> getExpense(@PathVariable("id") Long userId){
        Optional<Expense> expense = expenseRepository.findByUserId(userId);
        return expense.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
}

方式二:统一路径变量名与参数名

将路径中的变量名改为userId,与参数名保持一致,无需额外指定注解参数:

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class ExpenseController {
    @Autowired
    ExpenseRepository expenseRepository;
    @GetMapping("/expense/{userId}")
    public ResponseEntity<?> getExpense(@PathVariable Long userId){
        Optional<Expense> expense = expenseRepository.findByUserId(userId);
        return expense.map(response -> ResponseEntity.ok().body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
}
前端请求验证

你的前端axios请求代码逻辑正确,拼接后的URL格式为http://localhost:8080/api/test/expense/{userId},上述两种修改方式都能与前端请求匹配。

内容的提问来源于stack exchange,提问作者Mohammed Faraz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:35:24