Video tayyorlanmoqda
CORS xatosi nima uchun chiqadi va Spring'da uni to'g'ri qanday sozlaysiz?
Boshqa domendagi sahifa so'rov yuborsa, brauzer server ruxsat berganmi-yo'qmi Access-Control-Allow-* sarlavhalaridan qaraydi. Ruxsat yo'q bo'lsa, javobni JavaScript'ga bermaydi. Spring'da CORS'ni Security bilan birga, aniq domenlar ro'yxati bilan sozlaysiz.
📖 Javob
Holat: frontend https://app.shop.uz, API https://api.shop.uz. Brauzer murakkab so'rovdan (masalan, Authorization sarlavhali yoki JSON POST) oldin OPTIONS preflight yuboradi. Server to'g'ri javob bermasa, konsolda:
Access to fetch at 'https://api.shop.uz/orders' from origin 'https://app.shop.uz'
has been blocked by CORS policy
CORS — brauzer qoidasi. Postman yoki curl'da xato chiqmaydi, shuning uchun backend "menda hammasi ishlayapti" deydi, frontend esa ishlamayapti deydi.
Sozlash:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration c = new CorsConfiguration();
c.setAllowedOrigins(List.of("https://app.shop.uz"));
c.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
c.setAllowedHeaders(List.of("Authorization", "Content-Type"));
c.setAllowCredentials(true);
UrlBasedCorsConfigurationSource s = new UrlBasedCorsConfigurationSource();
s.registerCorsConfiguration("/api/**", c);
return s;
}
// SecurityFilterChain'da: http.cors(Customizer.withDefaults())
Ko'p uchraydigan xato — faqat @CrossOrigin yoki WebMvcConfigurer bilan sozlab, Security'ni unutish: preflight Security'da 401 olib qoladi. allowedOrigins("*") + allowCredentials(true) esa umuman taqiqlangan, xavfsizlik jihatdan ham noto'g'ri.
Ro'yxatdan o'ting, shunda o'rgangan savollaringiz belgilanadi va progressingiz saqlanadi.