【问题标题】:Angluar client cant resolve json from spring boot because of cors error由于 cors 错误,Angular 客户端无法从 Spring Boot 解析 json
【发布时间】:2021-01-04 18:11:22
【问题描述】:

我想创建一个 Angular 客户端,它从 localhost spring boot 服务器查询一些 json。 我的 HTTP Angular 服务看起来是这样的:

export class ProductService {
  private baseUrl = 'http://localhost:8080/priceoffer24/api/product';

  constructor(private http: HttpClient) { }

  public getProductById(id: number): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/${id}`);
  }

  public getProductByName(name: string): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/${name}`);
  }
  public getProductByBrand(brand: string): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/brand/${brand}`);
  }

  public getProductsList(): Observable<any>  {
    return this.http.get(`${this.baseUrl}/products`);
  }

  public getProductsNewest(): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/newest`);
  }

  public getProductsRandom(): any {
    return this.http.get(`${this.baseUrl}/products/random`);
  }

  public getProductsBySubcategorie(subcategorie: string): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/subcategorie/${subcategorie}`);
  }

  public getProductsBySubcategorieId(id: number): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/subcategorie/${id}`);
  }

  public getProductsByCategorie(categorie: string): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/categorie/${categorie}`);
  }

  public getProductsByCategorieId(id: number): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/categorie/${id}`);
  }

  public getProductsBySubcategorieAndCategorie(subcategorie: string, categorie: string): Observable<any> {
    return this.http.get(`${this.baseUrl}/products/subcategorie/${subcategorie}/categorie/${categorie}`);
  }

}

我现在的问题是出现以下 cors 错误。

Access to XMLHttpRequest at 'http://localhost:8080/priceoffer24/api/product/products/newest' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我必须在我的 Angular 应用程序或我的 spiring boot 应用程序中进行哪些更改?

【问题讨论】:

  • 您需要在 Spring Boot 应用中启用 CORS。

标签: java angular spring-boot http cors


【解决方案1】:

问题不在 Angular 应用程序中,您必须将客户端应用程序 URL(默认应为 http://localhost:4200)添加到 Api 服务器(春季启动)中的 Allowed Origins。

所以要解决这个问题,只需搜索如何修复服务器端。 也许这可以帮助https://spring.io/guides/gs/rest-service-cors/

【讨论】:

    【解决方案2】:

    在您的 Spring Boot Rest 控制器上使用 @CrossOrigin(origins = "http://example.com")

    这里 http://example.com 指的是 Angular 应用 URL(客户端应用)。这样做将只允许特定应用程序访问您的应用程序。

    如果您想允许所有主机访问您的控制器,则只需直接使用@CrossOrigin

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-14
      • 2019-07-26
      • 2020-11-05
      • 2018-12-26
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2020-05-02
      相关资源
      最近更新 更多