Quarkus服务新增学校数据返回HttpErrorResponse status 0问题求助
问题原因分析
1. 核心HTTP方法与接口不匹配
你目前新增、更新操作统一用PUT方法调用后端接口,后端未单独提供适配新增操作的POST接口,同时存在关联问题:
- 你的CORS配置大概率只放开了
GET/PUT/DELETE方法,未放开POST方法,新增请求触发跨域预检失败就会直接返回status 0错误 - 后端
PUT接口调用dao.save走em.merge逻辑,你新增时传id=-1,JPA会尝试匹配数据库中id=-1的记录,匹配失败会抛出异常,也会导致请求失败
2. DELETE接口参数不匹配
后端DELETE接口要求传入School实体、无路径参数,前端DELETE请求是拼接id到URL路径,两边逻辑不匹配,也可能触发跨域预检异常
3. 新增逻辑未调用正确的DAO方法
你的SchoolDao中已经写了专门用于新增的insert方法,通过em.persist实现新增,但是后端接口完全没有用到该方法
修复步骤
步骤1:修改后端SchoolResource代码
新增POST接口适配新增操作,同时修复DELETE接口参数逻辑:
package rest; import dao.SchoolDao; import model.School; import javax.inject.Inject; import javax.transaction.Transactional; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; @Path("school") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional public class SchoolResource { @Inject SchoolDao dao; @GET public List<School> getAll() { return dao.getAll(); } @GET @Path("/{id}") public School getById(@PathParam("id") int id) { return dao.getById(id); } // 保留PUT用于更新已有记录 @PUT public void update(School school) { dao.save(school); } // 新增POST接口用于新增记录 @POST public void insert(School school) { dao.insert(school); } // 修复DELETE接口,匹配前端传id的逻辑 @DELETE @Path("/{id}") public void delete(@PathParam("id") int id) { School school = dao.getById(id); if(school != null) { dao.delete(school); } } }
步骤2:修改前端SchoolService代码
区分新增和更新方法,适配后端接口:
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { School } from './model/school'; @Injectable({ providedIn: 'root' }) export class SchoolService { url = "http://localhost:8080/school" constructor(public http: HttpClient) { } getAll(): Observable<School[]> { return this.http.get<School[]>(this.url); } getById(id: number): Observable<School> { const url = `${this.url}/${id}`; return this.http.get<School>(url); } // 新增记录用POST add(school: School): Observable<School> { return this.http.post<School>(this.url, school); } // 更新已有记录用PUT update(school: School): Observable<School> { return this.http.put<School>(this.url, school); } delete(id: number): Observable<any> { const url = `${this.url}/${id}`; return this.http.delete(url); } }
步骤3:修改新增组件的保存逻辑
新增时不要传无效的id=-1,直接调用新增接口即可,id由数据库自增生成:
save(): void { const school = {name: this.name, street: this.street} as School; this.schoolService.add(school).subscribe(e => { this.router.navigateByUrl("/dashboard"); }); }
步骤4:检查CORS配置
确保Quarkus的CORS配置放开了POST方法,在application.properties中添加如下配置即可:
quarkus.http.cors=true quarkus.http.cors.origins=* quarkus.http.cors.methods=GET,PUT,POST,DELETE,OPTIONS quarkus.http.cors.headers=accept,origin,content-type,authorization
内容的提问来源于stack exchange,提问作者brainfock
相关产品推荐
相关产品推荐

