java - 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 应用程序中添加的所有可能的注释,但仍然给我一个错误。以前的线程也有与我的问题类似的描述,但是线程根本没有帮助,或者非常令人困惑,因为我的某些类不存在于我将建议的“代码”放在哪里。任何帮助表示赞赏!
解决方案
根据这条消息“这是我的控制台在运行我的 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);
}
推荐阅读
- error-handling - 如果没有结果,则从 for 循环返回结果或不返回任何内容
- python-3.x - 有没有一种方法可以遍历字典并在 while 循环中使用它?
- hashicorp-vault - 当以“没有已知的秘密 ID”开头时,hashicorp 保险库代理模板失败
- python - 在全球范围内设置 numpy.random.seed
- r - 用R提取字符串中间的字符串
- javascript - How to center a Scroll element with Overflow
- html - 301 将用户重定向到 https 协议,但前提是用户使用 http 协议
- reactjs - 如何在 Ubuntu 中使用 Shell 脚本从不同的目录启动 React 或 Node 应用程序
- python - Is there a way to have multiple instances of a model embedded into a single model field in Django?
- r - 使用 gtsummary 包的回归表的日志主题引发错误