Reputation: 157
I am using vue in the front end and spring boot in the back end .
I have used axios to make server call from the vue code .
Every thing was fine with GET ,POST requests.
When i try to make DELETE request it failed with 403
status and the error response is Invalid CROS request
.
But the same DELETE
request works In POSTMAN
I have tried the following solution mentioned in the another post and it didn't help me 1. added withCredentials: true in the request header
3.added @CrossOrigin annotation in the DELETE
api
This is how i created axios instance
const token = localStorage.token;
const instance = axios.create({
baseURL: "/",
headers: {
Authorization: token
}
});
making request as below
instance.delete(`/user/${username}`);
It throws 403
Invalid CROS Request
as response and its not hitting the server api too
Upvotes: 0
Views: 2061
Reputation: 157
It worked after removing a piece of code from the spring security configuration file which adds default crosconfiguration
@Beanpublic CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
applyPermitDefaultValues method of CorsConfiguration adds only GET,POST,HEAD methods
Upvotes: 0
Reputation: 532
You need to allow methods also
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer
{
@Override
public void addCorsMappings(CorsRegistry registry)
{
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST","PUT", "DELETE");
}
}
or if you are configuring at controller and method level
@Controller
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class HomeController
{
@CrossOrigin(origins = "http://example.com")
@DeleteMapping("/{username}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUserByUsername(@PathVariable("username") String username)
{
User user= userRepository.findByUsername(username);
userRepository.delete(user);
}
}
Upvotes: 2