这是我的控制台在运行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 app中的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应用程序中添加的所有可能的注解,但是仍然给了我一个错误。以前也有一些线程对我的问题有类似的描述,但是这些线程根本没有帮助,或者很难理解,因为我的线程中有一些类不存在,我应该把建议的“代码”放在哪里。感谢您的帮助!
2条答案
按热度按时间fzwojiic1#
很好的问题,因为它给我们带来了这个结局
/
问题。简而言之,
http://localhost:4200
以及http://localhost:4200/
是完全不同的,即使它调出相同的页面或相同的资源。您的浏览器正在抱怨:
前端javascript是
origin 'http://localhost:4200'
.但是,在后端应用程序中,您配置了
@CrossOrigin(origins = "http://localhost:4200/")
.把它改成
@CrossOrigin(origins = "http://localhost:4200")
或者只是@CrossOrigin
.xqnpmsa82#
根据这条信息“这是我的控制台在运行我的angular应用程序时所说的(localhost:4200)“,这是cors问题。必须在springboot应用程序中配置corsfilter,如下所示: