Angular调用本地SpringBoot接口出现404 Not Found错误求助
解决Angular调用SpringBoot接口的404与CORS问题
我来帮你一步步排查和解决这个问题,你的核心问题出在代理配置错误和不必要的CORS代理工具使用上,咱们逐个解决:
1. 修正Angular代理配置(proxy.conf.json)
你的代理配置里target写了具体的接口路径http://localhost:51535/company/BABA,这会导致请求路径拼接错误。代理的逻辑是:把匹配到的路径(比如/company/BABA)追加到target后面,所以正确的target应该是SpringBoot服务的根地址,而不是具体接口。
修改后的proxy.conf.json:
{ "/company/*": { "target": "http://localhost:51535", "secure": false, "logLevel": "debug", "changeOrigin": true // 新增这个配置,解决跨域时的Origin校验问题 } }
2. 移除CORS-anywhere,改用代理路径
既然已经配置了Angular代理,就不需要再依赖https://cors-anywhere.herokuapp.com/了,直接用相对路径调用即可,这样请求会自动被代理转发到SpringBoot,同时避免CORS问题。
修改你的服务代码:
import { Injectable } from '@angular/core'; import {HttpClient} from '@angular/common/http' import {IData} from './data'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CompanyserviceService { // 改用相对路径,代理会自动转发到SpringBoot private _url: string = "/company/BABA"; constructor(private http: HttpClient) { } getData(): Observable<IData[]>{ return this.http.get<IData[]>(this._url); } }
3. 确保启动Angular时加载代理配置
启动Angular项目时,必须指定代理配置文件,否则代理不会生效:
ng serve --proxy-config proxy.conf.json
4. 验证SpringBoot接口的可用性
最后要确认你的SpringBoot接口本身是正常的:
- 直接在浏览器或Postman中访问
http://localhost:51535/company/BABA,看是否能返回预期数据 - 检查SpringBoot的接口路径是否拼写正确(比如
@GetMapping("/company/BABA")有没有写错)
按照以上步骤修改后,应该就能解决404和CORS问题了。
内容的提问来源于stack exchange,提问作者Ojasvi Pandya
相关产品推荐
相关产品推荐

