我收到一个org.springframework.web.bind.MissingPathVariableExcepti



我使用的是spring-boot RestApi后端和react前端。我正在使用axios从数据库获取数据

const API_URL_EX = 'http://localhost:8080/api/test/expense';
getExpense(userId){
return axios.get(API_URL_EX + '/'+userId);
}
componentDidMount(){
const currentUser = AuthService.getCurrentUser();
let userId = {...this.state.userId};
userId = currentUser.id;
this.setState({userId});
UserService.getExpense(userId).then((res) =>{
this.setState({expense: res.data});
},
error => {
this.setState({
content:
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
});
}
);
}
@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class ExpenseController {
@Autowired
ExpenseRepository expenseRepository;
@GetMapping("/expense/{id}")
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));
}
}

我试图从mysql数据库中获取数据,但我收到了这个错误,我将正确的id作为路径变量传递

[org.springframework.web.bind.MissingPathVariableException: Required URI template variable 'userId' for method parameter type Long is not present]

除非指定路径变量的名称,否则路径变量的名字和方法参数的名字应该匹配。只要将id更改为userId,它就会工作。

@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));
}

另一个选项是指定路径变量的名称。在这种情况下,名称不必匹配。

@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));
}

您可以阅读本文来了解有关@PathVariable注释的更多信息。

相关内容

最新更新