skip to Main Content

When I make HTTP POST request, I got this message on my screen. How can I solve this problem? I don’t use any GET annotation or request.

HTPP REQUEST : http://localhost:9000/user/register?username=a&password=1

Console Error

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

JavaScript

<script>
document.getElementById("signupbtn").addEventListener("click",function(){
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;
    const xhr = new XMLHttpRequest(); 
    xhr.open("POST","http://localhost:9000/user/register?username="+username+"&password="+password);
    xhr.send();
  })

</script>

Controller

@PostMapping("/register")
ResponseEntity<String> addUser(@RequestParam("username") String username,@RequestParam("password") String password) {
    userService.addUser(username, password);
    return ResponseEntity.ok("User added succesfully");
}

Service

public void addUser(String username,String password){
    userRepository.save(new User(username,password));
       
}

3

Answers


  1. Chosen as BEST ANSWER

    The problem is when i send to request. This is a GET request not POST . I changed the PostMapping To GetMapping problem is solved. I think there is missunderstanding about POST and GET mapping


  2. Here is solution from the REQBIN

    Please refer the link and execute the code and apply in your project

    let xhr = new XMLHttpRequest();
    
    xhr.open("POST", "https://reqbin.com/echo/post/json");
    
    let data = {
      "Id": 78912,
      "Customer": "Jason Sweet",
    };
    
    xhr.onload = () => console.log(xhr.status);
    
    xhr.send(data);
    
    Login or Signup to reply.
  3. there is nothing wrong with your code , it should work unless you do have restriction in your app security config like (allowedMethods )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search