Java 由于cors错误,Angluar客户端无法从spring boot解析json

Java 由于cors错误,Angluar客户端无法从spring boot解析json,java,angular,spring-boot,http,cors,Java,Angular,Spring Boot,Http,Cors,我想创建一个angular客户机,它从本地主机spring引导服务器查询一些json。 我的HTTP Angluar服务看起来是这样的: export class ProductService { private baseUrl = 'http://localhost:8080/priceoffer24/api/product'; constructor(private http: HttpClient) { } public getProductById(id: number)

我想创建一个angular客户机,它从本地主机spring引导服务器查询一些json。 我的HTTP Angluar服务看起来是这样的:

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}`);
  }

}
在angular应用程序或spiring boot应用程序中,我需要更改什么?

使用
@CrossOrigin(origins=)http://example.com”
在您的spring boot rest控制器上

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


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

问题不在Angular应用程序中,您必须添加客户端应用程序URL(默认为http://localhost:4200)到Api服务器中允许的源(spring引导)

因此,要解决这个问题,只需搜索如何修复服务器端。
这可能会有所帮助

您需要在spring boot应用程序中启用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.