首页 > 解决方案 > Angular 应用程序未从部署在 Google Kubernetes Engine 中的 Spring Boot API 呈现数据

问题描述

我有一个有线错误,

我在本地机器上运行 Angular 应用程序。我在 Google Kubernetes Engine 中运行了 Spring Boot Application pod。

除了一个端点之外,每个端点都可以正常工作。

错误日志:


Angular is running in development mode. Call enableProdMode() to enable production mode.
add-sales:1 Access to XMLHttpRequest at 'http://34.72.237.38:8080/vehicles/2' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
add-sales.component.ts:63 Error in getting the single vehicle :  
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://34.72.237.38:8080/vehicles/2", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://34.72.237.38:8080/vehicles/2: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://34.72.237.38:8080/vehicles/2"
__proto__: HttpResponseBase

当我在浏览器中点击上述 URL 时,数据以 JSON 格式呈现。当我从服务类调用此服务时,我不知道为什么它没有在 Component.ts 文件中显示。

服务等级


@Injectable({
  providedIn: 'root'
})
export class VehicleDetailsService {

  vehicleDetails : VehicleDetails;

  
  
  url="http://34.72.237.38:8080";
  // url = "http://localhost:8080";

  constructor(private http: HttpClient) { }



  getVehicleDetails(id : number){
    return this.http.get<VehicleDetails>(this.url+`/vehicle/${id}/vehicleDetail`);
  }
}

组件类:


getSingleVehicle(){
    return this.vehicle_service.getSingleVehicles(this.vehicleID)
      .subscribe(res => {
        this.vehicle = res;
        console.log("Response for single vehicle : ",this.vehicle);
      },
      err=>{
        console.log("Error in getting the single vehicle : ",err);
      })
    }

Spring Boot 控制器类


@RestController
@CrossOrigin
public class VehicleController {
    
    @Autowired
    public VehicleService vehService;
    
    @GetMapping("/vehicles/{id}")
    public Optional<Vehicle> getVehicleById(@PathVariable Long id) {
        return vehService.getSingleVehicle(id);
    }

}

这是我的弹簧安全配置:


@Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http.authorizeRequests().antMatchers("/").permitAll().and()
        .authorizeRequests().antMatchers("/console/**").permitAll();
    http.csrf().disable();
    http.headers().frameOptions().disable();

在这里,我允许所有网址,但我仍然无法以角度渲染数据。

标签: javaangularspring-bootkubernetes

解决方案


错误消息显示不允许从本地开发机器 ( localhost:4200) 到部署的应用程序的跨源请求。由于您@CrossOrigin在控制器上存在注释,如您的问题所示,因此必须存在不同类型的问题。假设:在添加@CrossOrigin. 另一种选择可能是过滤 CORS 标头的反向代理。


推荐阅读