0

I wrote a request(method:delete) in my ajax. I used a deleteMapping in my controller. And when I trigger this request, I got a 400 error. But in browser I can see the data projectIdenter image description here

The console said Required String parameter 'projectId' is not present

Total log

2017-08-14 13:06:11.296  WARN 8584 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound             : Request method 'DELETE' not supported
2017-08-14 13:06:11.296  WARN 8584 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported

2017-08-14 12:32:57.239  WARN 8584 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'projectId' is not present

Here is the ajax

$('#delete-project-btn').on('click', function() {
    if (cur != null) {
        alert(cur);
        if(window.confirm('sure?')) {
            $.ajax({
                url : '/index/'+cur,
                type : 'delete',
                dataType : 'text',
                data : {
                    projectId : cur
                },              
            });
         }
    } 

})

and my controller

     @DeleteMapping("/index/{projectId}")
     public String deleteProject(@PathVariable("projectId") int id) {
        System.out.println(id);
//        projectRepository.delete(Integer.valueOf(id));
        return "redirect:/index";
    }

Where is the problem?

M Chen
  • 133
  • 1
  • 3
  • 15
  • 2
    In your ajax request , you should pass projectid as part of request param not request body. – Barath Aug 14 '17 at 04:38

1 Answers1

4

As per the commented link below ,

If a DELETE request includes an entity body, the body is ignored

$('#delete-project-btn').on('click', function() {
    if (cur != null) {
        alert(cur);
        if(window.confirm('sure?')) {
            $.ajax({
                url : '/index?projectId='+cur,
                type : 'delete',
                dataType : 'text'

            });
         }
    } 

})
Barath
  • 5,093
  • 1
  • 17
  • 42
  • read full discussion here https://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request – Barath Aug 14 '17 at 04:42
  • how to change my controller to get the id? – M Chen Aug 14 '17 at 04:55
  • I think your controller is right just try changing the ajax request url as updated above – Barath Aug 14 '17 at 04:57
  • I update the controller and ajax as before, it got the id, but it failed to redirect, and has another error as I write. – M Chen Aug 14 '17 at 05:08
  • you can redirect from ui itself let delete endpoint , delete the resource ! make it a void – Barath Aug 14 '17 at 05:11