Connor
Connor

Reputation: 43

Spring Boot error "Request method 'POST' not supported" with Ajax function

I have a page with url "http://localhost:8080/clientes/cadastrar" and I have a button in this page, when pressed the button opens a modal to insert some information(name,email,etc). The problem is that when I click the "Save button" in this modal, with an onclick function to call the Ajax function, I get the following error:

2021-03-11 16:30:31.973  WARN 1200 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]

Here is the AJAX function:

<script th:src="js/AddEmailCliente.js" th:fragment="js"></script>
    <script th:inline="javascript" th:fragment="inlinescript">
function salvarEmail() {
        
        var cliente = /* [[cliente]] */ 0;
        var nome = Document.getElementById('nome').value;
        var email = Document.getElementById('email').value;
        var envio_cobranca = Document.getElementById('envio_cobranca').checked ? true : false;
        
        
        $.ajax({
            url : "/emails/salvar",
            type : 'POST',
            contentType : 'application/json',
            data : JSON.stringify({
                idcliente : 'cliente.idcliente',
                nome : nome,
                email : email,
                envio_cobranca : envio_cobranca
            }),
            success : function(data) {
                session = data.session;
            }
        });
         
         
     } 
    
    </script>

Here is the controller:

@Controller
@RequestMapping("/emails")
public class EmailController {

    @Autowired
    EmailService service;
    
    @Autowired
    ClienteService clienteService;
    
    
    @PostMapping("/salvar")
    public String salvar(BindingResult result, RedirectAttributes attr, @RequestParam Long idcliente, @RequestParam String nome, 
            @RequestParam String email, @RequestParam boolean envio_cobranca) {
            Email emails = new Email();
            Cliente cliente = clienteService.buscarPorId(idcliente);
            //email.
        if(service.emailJaExiste(email)) {
            attr.addFlashAttribute("fail", "Já existe este email.");                
        }else {
            emails.setEmail(email);
            emails.setNome(nome);
            emails.setCliente(cliente);
            emails.setEnvio_cobranca(envio_cobranca);
            service.salvar(emails);
            attr.addFlashAttribute("success", "E-mail inserido com sucesso.");              
        }   
        return "redirect:/emails/listar";
    }   

And in the navigator console I can see:

Request URL: http://localhost:8080/emails/salvar
Request Method: POST
Status Code: 405 
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin

So the URL is correct.

Button code:

<div class="modal-footer">
                        <button id="add_email" type="button"
                            class="btn btn-primary waves-effect waves-light"
                            th:id="${'addEmail_emails/salvar/' + cliente.id}"
                            onclick="salvarEmail();">Salvar</button>

Additionaly, the response header shows:

HTTP/1.1 405
Allow: GET
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Thu, 11 Mar 2021 21:28:40 GMT
Keep-Alive: timeout=60
Connection: keep-alive

Can this be related to the fact that I use a modal (and the URL doesn't change when I open the modal, keeps a non-related with this email method URL "http://localhost:8080/clientes/cadastrar"), or the fact that I am using an onclick function instead of a form submit?

Upvotes: 0

Views: 818

Answers (3)

TanvirChowdhury
TanvirChowdhury

Reputation: 2445

Try sending the csrf token and header along with your POST request.

function salvarEmail() {
        var token = $('#_csrf').attr('content');
        var header = $('#_csrf_header').attr('content');

        var cliente = /* [[cliente]] */ 0;
        var nome = Document.getElementById('nome').value;
        var email = Document.getElementById('email').value;
        var envio_cobranca = Document.getElementById('envio_cobranca').checked ? true : false;


        $.ajax({
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader(header, token);
            },
            url : "/emails/salvar",
            type : 'POST',
            contentType : 'application/json',
            data : JSON.stringify({
                idcliente : 'cliente.idcliente',
                nome : nome,
                email : email,
                envio_cobranca : envio_cobranca
            }),
            success : function(data) {
                session = data.session;
            }
        });


    }

Upvotes: 1

palbok
palbok

Reputation: 58

I think you need to CSRF token. because of Spring Security

Upvotes: 1

Mike Adamenko
Mike Adamenko

Reputation: 3002

Try to change @PostMapping("/salvar") to @PostMapping(path = "/salvar")

Upvotes: 0

Related Questions