Saradha
Saradha

Reputation: 157

Axios DELETE request failes only in the browser with 403 "Invalid CORS request" as response

  1. I am using vue in the front end and spring boot in the back end .

  2. I have used axios to make server call from the vue code .

  3. Every thing was fine with GET ,POST requests.

  4. When i try to make DELETE request it failed with 403 status and the error response is Invalid CROS request.

  5. 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

  1. added headers: {'X-Requested-With': 'XMLHttpRequest','X-CSRFToken': 'your token here'}

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

Answers (2)

Saradha
Saradha

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

Muni Kumar Gundu
Muni Kumar Gundu

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

Related Questions