首页 > 解决方案 > Angular Web 应用程序无法正确连接到我的 Spring Boot 应用程序 API

问题描述

这就是我的控制台在运行我的 Angular 应用程序时所说的内容 (localhost:4200) –</p>

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 服务——</p>

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 中的控制器类 -</p>

@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;
    }
}

应用类——</p>

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

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

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

标签: javaangularspringspring-boot

解决方案


根据这条消息“这是我的控制台在运行我的 Angular 应用程序时所说的(本地主机: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);
 } 

推荐阅读