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

Angular调用Quarkus接口报HttpErrorResponse状态0问题求助

问题排查与解决方案

1. 前端代码错误修复

首先修改school.service.ts中的问题:

  • 接口地址缺少http://协议前缀,浏览器会把它识别为当前Angular服务的相对路径,导致请求地址错误
  • getById方法中的地址存在拼写错误(locahlost应为localhost),且路径参数没有动态替换
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 {
  // 补充http协议前缀
  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);
  }
}

建议补充请求错误回调,方便排查具体报错:

// dashboard.component.ts ngOnInit部分修改
ngOnInit(): void {
  this.schoolService.getAll().subscribe({
    next: e => this.schools = e,
    error: err => console.error('请求失败详情:', err)
  });
}

2. 后端代码错误修复

修改SchoolResource类中getById方法的路径注解配置:

  • 当前@Path("id")会把接口地址固定为/school/id,无法匹配路径参数,需要改为@Path("{id}")才能绑定@PathParam的参数值
@Path("school")
@Produces(MediaType.APPLICATION_JSON)
@Transactional
public class SchoolResource {
    @Inject
    SchoolDao dao;

    @GET
    public List<School> getAll() {
        return dao.getAll();
    }

    // 修正路径注解,匹配路径参数
    @Path("{id}")
    @GET
    public School getById(@PathParam("id") int id) {
        return dao.getById(id);
    }
}

3. Quarkus CORS配置校验

不需要手动写CORS Filter,直接在src/main/resources/application.properties中添加以下配置即可:

# 开启CORS
quarkus.http.cors=true
# 允许的来源,默认Angular本地开发端口为4200
quarkus.http.cors.origins=http://localhost:4200
quarkus.http.cors.methods=GET,POST,PUT,DELETE,OPTIONS
quarkus.http.cors.headers=accept,origin,content-type,authorization

配置完成后先单独测试后端接口是否正常:在浏览器直接访问http://localhost:8080/school,确认能返回JSON格式的学校列表数据,再启动Angular项目测试即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:06:01