CodexBloom - Programming Q&A Platform

AJAX POST request not handling CORS preflight in Angular 12 with Spring Boot backend

๐Ÿ‘€ Views: 46 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
angular spring-boot cors TypeScript

I'm relatively new to this, so bear with me... I'm having trouble with an AJAX POST request in my Angular 12 application where I'm trying to send data to a Spring Boot backend. The question arises when I perform the request; I'm receiving a CORS preflight behavior in the console: "Access to XMLHttpRequest at 'http://localhost:8080/api/data' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." Iโ€™ve made sure to set the appropriate CORS configuration on the Spring Boot side, but it doesnโ€™t seem to be working as expected. On the Spring Boot side, I have the following CORS configuration: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:4200").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*"); } } ``` On the Angular side, I'm using HttpClient for the AJAX POST: ```typescript import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) { } sendData(data: any) { return this.http.post('http://localhost:8080/api/data', data); } } ``` Iโ€™ve checked that the Spring Boot server is running and accessible from the browser. I am able to make successful GET requests without any issues. However, when I try to do a POST, the preflight request fails, and I need to figure out what the question might be. I've also tried adding `@CrossOrigin` annotations on my controller methods, but that didn't resolve the scenario either. Any suggestions on what else I could check or try to resolve this CORS scenario? For context: I'm using Typescript on Windows. Has anyone else encountered this? This is for a microservice running on Linux. I'm open to any suggestions.