Gabi Onea
Gabi Onea

Reputation: 53

Passing variables from frontend to backend

I'm working on a website that has a backend done with Java (hosted using Spring) and frontend managed by Javascript. Now, I've managed to send code from the backend to frontend using a RestController but I can't managed to send data from the frontend to the backend. To be more specify I'm trying to create a login form with backend validation.

HTML Form code:

<form ng-submit="login">
  <input type="text" ng-model="form.username" placeholder="username">
  <input type="password" ng-model="form.password" placeholder="password">
  <input type="submit" value="Login">
</form>

Javascript login code:

function auth($scope, $http, AppSettings, $state) {
  'ngInject';
  $scope.form = {};

  $scope.login = () => {
    $http({
      method: 'POST',
      url: AppSettings.getApiUrl('/login'),
      data: {
        user: $scope.form.username,
        password: $scope.form.password,
      },
      // data: {}
    }).then(response => {
      if (response) {
        console.log(response.data);
        localStorage.setItem('token', response.data.token);

        $state.go('main');
      }
    }).catch(error => {
      console.log(error);
    });
  };
}

Java Login Handler:

@RestController
public class LoginHandler  {

    private static final Logger log = LoggerFactory.getLogger(LoginHandler.class);


    @RequestMapping("/login")
    public void getLoginInfo(@RequestParam Map<String,String> requestParams) {
        RestTemplate restTemplate = new RestTemplate();
        User user = restTemplate.getForObject("http://localhost:3003/auth", User.class);
        log.info(user.toString());

    }

}

Upvotes: 3

Views: 9322

Answers (1)

31piy
31piy

Reputation: 23859

When you send the data to the back-end using AngularJS and use the data key to set the parameters, the information is actually sent in a request body instead of request parameters.

So, on the Spring MVC controller, you rather use a @RequestBody to assign the values back to the Map<String, String>. Change this line:

public void getLoginInfo(@RequestParam Map<String,String> requestParams) {

to this:

public void getLoginInfo(@RequestBody Map<String,String> requestParams) {

Upvotes: 1

Related Questions