fetch获取Spring Boot后端Mono对象返回undefined求助
问题描述
开发时从客户端向Spring Boot后端发起GET请求,预期获取封装Shift对象的Mono类型响应,但客户端接收到的返回数据为undefined,无法正常读取接口返回结果,相关原始实现代码如下:
原始客户端代码
function getShift (ID: String) { fetch("http://localhost:8080/shifts/?ID=" + "shiftID", { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", }, credentials: "include", }) .then( (response) => { response.json(); } ) .then((data) => console.log(data, "this is the data")) .catch((err) => console.log(err)); }
原始服务端代码
@GetMapping (produces = "application/json") private Mono<ResponseEntity<Shift>> getShift(String ID) { return shiftService.getShift(ID).map(u->ResponseEntity.status(HttpStatus.OK).body(u)); }
问题原因
- 前端fetch第一个回调无返回值:箭头函数使用大括号包裹逻辑时,不会自动返回内部执行结果,代码里只调用了
response.json()但没有做return操作,导致下一个链式then接收到的参数直接是undefined,这是返回数据异常的核心原因。 - 前端请求参数硬编码错误:URL拼接时直接写死了字符串
"shiftID",没有使用函数传入的ID形参,实际请求携带的参数值完全不符合业务预期。 - 后端接口方法权限错误:接口方法定义为
private私有方法,Spring无法对私有方法做路由映射代理,会直接导致接口无法正常响应请求。 - 后端参数未做绑定:方法入参ID未添加
@RequestParam注解,无法自动接收URL上携带的ID查询参数,业务层拿不到正确ID就无法查询到对应Shift数据。 - 后端路由未配置路径:
@GetMapping注解未指定映射路径/shifts,和前端请求的路径不匹配,会直接返回404错误。
修复后代码
客户端修复
function getShift (ID: String) { // 替换硬编码参数,使用传入的ID值拼接URL fetch(`http://localhost:8080/shifts/?ID=${ID}`, { method: "GET", headers: { "Content-Type": "application/json", Accept: "application/json", }, credentials: "include", }) .then((response) => { // 返回response.json()的执行结果,保证链式调用能拿到解析后的JSON数据 return response.json(); }) .then((data) => console.log(data, "this is the data")) .catch((err) => console.log(err)); }
如果要简化写法,第一个then也可以写成无大括号的箭头函数,会自动返回执行结果:
.then(response => response.json())
服务端修复
// 指定映射路径为/shifts,将方法改为public,参数添加@RequestParam注解绑定查询参数 @GetMapping(value = "/shifts", produces = "application/json") public Mono<ResponseEntity<Shift>> getShift(@RequestParam String ID) { return shiftService.getShift(ID).map(u->ResponseEntity.status(HttpStatus.OK).body(u)); }
如果前后端端口不一致,还需要在后端Controller类上添加@CrossOrigin注解配置跨域允许,否则前端会被跨域策略拦截无法拿到响应。
内容的提问来源于stack exchange,提问作者Hassan Raza
相关产品推荐
相关产品推荐

