【问题标题】:Angular web app can't properly connect to my Spring Boot app APIAngular Web 应用程序无法正确连接到我的 Spring Boot 应用程序 API
【发布时间】:2021-07-20 08:12:49
【问题描述】:

这是我的控制台在运行我的 Angular 应用程序时显示的内容 (localhost:4200) –

Access to XMLHttpRequest at 'http://localhost:8090/api/orders' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED :8090/api/orders:1
ERROR HttpErrorResponse core.js:6210 
defaultErrorLogger @ core.js:6210

这是我在 Angular Web 应用中的 API 服务 –

export class ApiService {

  constructor(private http: HttpClient) { }

  baseAPI = 'http://localhost:8090/api/';
  orderId: number;
  orderAdd = {} as Order;

  getOrderList(): Observable<any> {
    return this.http.get(this.baseAPI + 'orders');
  }
  
}

这是我在 Spring Boot 应用 API 中的控制器类 -

@RestController
@CrossOrigin(origins = "http://localhost:4200/")
@RequestMapping("/api")
public class OrderAndBillingController {

    @Autowired
    private OrderRepository orderRepo;
    @Autowired
    private CafeClerk clerk;

    public OrderAndBillingController(CafeClerk clerk) {
        this.clerk = clerk;
    }

    @GetMapping(path = "/orders", produces = "application/json")
    public List<Order> getOrderList(){
        List<Order> list = new ArrayList<Order>();
        orderRepo.findAll().forEach(al -> list.add(al));
        return list;
    }
    @PostMapping(path = "/add", produces = "application/json")
    public void addOrder(@RequestBody Order order){
        orderRepo.save(order);
    }
    @PutMapping(path = "/update", produces = "application/json")
    public void updateOrder(@RequestBody Order order){
        orderRepo.save(order);
    }
    @DeleteMapping(path = "/delete/{id}", produces = "application/json")
    public void deleteOrder(@PathVariable("id") Order order){
        orderRepo.delete(order);
    }
    @GetMapping(path = "/orders/regular-bill")
    public OrderBill getTotalRegularBill() {
        var listOrder = this.orderRepo.findAll();
        OrderBill bills = new RegularBill(this.clerk);
        bills.setOrderList(listOrder);
        return bills;
    }
    @GetMapping(path = "/orders/discounted-bill")
    public OrderBill getTotalDiscountedBill() {
        var listOrder = this.orderRepo.findAll();
        OrderBill bills = new DiscountedBill(this.clerk);
        bills.setOrderList(listOrder);
        return bills;
    }
}

应用类——

@SpringBootApplication
@ComponentScan({"com.company.ws"})
public class OrderBillingWsApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderBillingWsApplication.class, args);
    }
}

我确实尝试了在我的 Spring Boot 应用程序中添加的所有可能的注释,但仍然给我一个错误。 以前的线程也有与我的问题类似的描述,但是线程根本没有帮助,或者很容易让人困惑,因为我的一些类不存在于我将建议的“代码”放在哪里。任何帮助表示赞赏!

【问题讨论】:

    标签: java angular spring spring-boot


    【解决方案1】:

    非常好的问题,因为它给我们带来了/ 问题。

    简而言之,http://localhost:4200http://localhost:4200/ 是完全不同的,即使它们拉取的是相同的页面或相同的资源。

    您的浏览器在抱怨:

    Access to XMLHttpRequest at 'http://localhost:8090/api/orders' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    

    前端的javascript是origin 'http://localhost:4200'

    但是,在您的后端应用程序中,您配置了@CrossOrigin(origins = "http://localhost:4200/")

    将其更改为@CrossOrigin(origins = "http://localhost:4200") 或简单的@CrossOrigin

    【讨论】:

      【解决方案2】:

      根据此消息“这是我的控制台在运行我的 Angular 应用程序 (localhost:4200) 时所说的内容”,这是一个 CORS 问题。您必须在 Springboot 应用程序中配置 CorsFilter,如下所示:

      @Bean 
      public CorsFilter corsFilter() { 
      final UrlBasedCorsConfigurationSource source =     new UrlBasedCorsConfigurationSource();     
      final CorsConfiguration config = new CorsConfiguration();
      config.setAllowCredentials(true);
      config.addAllowedOrigin("*");
      config.addAllowedHeader("*");
      config.addAllowedMethod("OPTIONS");
      config.addAllowedMethod("HEAD");
      config.addAllowedMethod("GET");
      config.addAllowedMethod("PUT");
      config.addAllowedMethod("POST");
      config.addAllowedMethod("DELETE");
      config.addAllowedMethod("PATCH");
      source.registerCorsConfiguration("/**", config); return new CorsFilter(source);
       } 
      

      【讨论】:

      • 谢谢你,但我很困惑我该把它放在哪里?它在我的应用程序类上吗?
      • 我实际上试图把它放在 Application 类上,但顺便说一句,我仍然遇到同样的错误。
      • 你可以把它放在你的应用程序类或任何其他带有@Configuration注解的类中。但我已经看到 justthink 检测到了这个问题。如果您愿意,您可以从控制器中删除 cors 配置并制作一个通用的 cors 过滤器,就像我展示的那样。再放一行 config.setAllowedOrigins(Arrays.asList("localhost:4200")); 我忘了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2020-03-22
      • 2020-06-16
      相关资源
      最近更新 更多