Pass javascript response variable to spring controller function

The following javascript code works with the appearance of the facebook login window and allows the user to log in. The response values ​​are captured, and I know that it works when warnings appear during installation, but I cannot pass the value back to the controller method.

@RequestMapping(value ="/getAccessToken" , method = RequestMethod.POST) public @ResponseBody String getAccessToken(@RequestBody String token){ System.out.println(token); return token; } 

Javascript method:

  function doLogin() { FB.login(function(response) { alert(response); console.log(response); if (response.authResponse) { alert(response.authResponse.userID); alert(response.authResponse.accessToken); var Token = response.authResponse.accessToken; alert(Token); $.ajax({ type: "POST", url: "/HelloController/getAccessToken", data: Token, success: function (result) { alert("Token"); }, error: function (result) { alert("oops"); } }); document.getElementById('loginBtn').style. display = 'none'; getUserData(); }}, {perms:'manage_pages', scope: 'email,public_profile', return_scopes: true}); }; 

The error I am getting is the following:

 WARN 25660 --- [nio-8080-exec-9] osweb.servlet.PageNotFound : Request method 'POST' not supported 

Rate the answers.

+5
source share
1 answer

The problem may be that you are using a new version of jQuery which, by default, sends query data as message form data, not JSON. Try changing your ajax call to the following. Form data will not be recognized by your controller, so if so, you should see 404.

 $.ajax({ type: "POST", traditional: true, url: "/HelloController/getAccessToken", data: JSON.stringify(Token), success: function (result) { alert("Token"); }, error: function (result) { alert("oops"); } }); 

For reference, see this post: Send JSON data via POST (ajax) and get json response from Controller (MVC)

+2
source

Source: https://habr.com/ru/post/1237186/


All Articles