[英]Unable to hit spring boot Rest API from my angular 5 project
[英]Angular 2 REST API call to Spring Boot project
我正在嘗試創建 angular 2 項目。 在我的項目中,我將使用 REST 調用 Spring Boot 微服務來進行數據庫插入和更新。
是的,您必須使用 CORS 請求進行 api 調用。 對於您的端點,只需在發出請求時指定完整的 url http://localhost:8080/api ,而在生產中使用相同的源 /api。 您可能希望使用 Spring 為 prod 提供 dist 文件夾的內容。 您只需要弄清楚如何設置一個可以檢查環境的變量,以便您可以切換 url。
對於開發 api,您需要確保 CORS 配置正確,即處理 OPTION 請求並設置正確的標頭,否則瀏覽器會抱怨。
在我的應用程序中,啟用 CORS 后,在我的 angular 項目(在 VSCode 中)中,在 app.component.ts 中我有
private baseURL:string='http://localhost:8080/';
private getUrl:string = this.baseURL + '/local/';
我得到的看起來像:
getWelcomeMessage(): Observable<any>{
return this.httpClient.get(this.getUrl, {responseType: 'json'});
}
我的訂閱看起來像
this.getWelcomeMessage().subscribe(
welcome=>{
console.log(Object.values(welcome));
this.welcome=<any>Object.values(welcome);
}
);
對於導出接口:
export interface Welcome{
message:string;
}
這讓我可以在 IntelliJ IDEA 中的 spring 引導后端向我的 Angular 前端顯示一條歡迎消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.