java - 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();
在这里,我允许所有网址,但我仍然无法以角度渲染数据。
解决方案
错误消息显示不允许从本地开发机器 ( localhost:4200
) 到部署的应用程序的跨源请求。由于您@CrossOrigin
在控制器上存在注释,如您的问题所示,因此必须存在不同类型的问题。假设:在添加@CrossOrigin
. 另一种选择可能是过滤 CORS 标头的反向代理。
推荐阅读
- c# - 如何将相机夹在鼠标 Y 轴上?
- javascript - 当图像以角度加载时显示加载图标
- reactjs - 在反应中通过邮件发送日历(谷歌,苹果等)
- heroku - Heroku dyno 小时数是如何计算的?
- websocket - WebSocket ping 可以在消息中间发生吗?
- javascript - 尽管异步操作中有另一个状态更新,但 React 是否有理由立即重新渲染?
- react-native - 如何限制平移并在我的 MapView 上只显示一个城市?
- flutter - 在 iphone 上安装后,flutter 应用程序崩溃
- docker - 如何通过“localhost”在两个单独的 docker 容器之间进行通信?
- api - 在何处使用独立 API Connect 和 DataPower