When attempting to make an HTTP request from my Angular application (running on localhost:4200) to my Spring Boot backend (running on localhost:8081), I encounter a CORS policy error. The error message is:
Access to XMLHttpRequest at 'http://localhost:8081/api/houses/1' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have completed the add functionalities and they work fine, but this issue is triggered when I try to update the information of a house. I’m confused because the POST (add) and PATCH (update) requests are coming from the same origin.
I also encountered the CORS issue when trying to load the houses on the house-list page. I resolved it by adding the web configuration to the backend (Spring Boot) which now looks like this:
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("/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("Access-Control-Allow-Origin")
.allowCredentials(true);
}
}
I added .allowCredentials(true);
I also tried adding the following to application.properties:
spring.web.cors.allowed-methods=*
spring.web.cors.allowed-headers=*
I also used a proxy configuration in Angular:
"/api": {
"target": "http://localhost:8081",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
},
"/uploads": {
"target": "http://localhost:8081",
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
}
And started Angular with: ng serve –proxy-config proxy.conf.json
I tested the backend CORS with the following curl command:
-H "Content-Type: application/json"
-d '{"name": "Updated House", "location": "Updated Location"}'
This command did not trigger the CORS issue.
I also attempted to use CORS Anywhere but struggled with implementation, so I abandoned that approach.
It’s worth mentioning that I get the same issue when trying to load the 3D model (which is a 3D representation of the house). However, loading the image of the house works fine. Adding a house and loading the image from the server do not result in CORS errors, but updating the house and loading the 3D model (from the same file where the image is) do.
Thank you for supporting to fix this issue. I have tried all of the above steps, but none of them have resolved the problem. It’s getting a little frustrating.
5