Currently, I am developing a website with Java on the backend (hosted via Spring) and Javascript managing the frontend. Although I have successfully sent code from the backend to the frontend using a RestController, I am facing difficulties in sending data from the frontend to the backend. Specifically, my goal is to create a login form with backend validation.
Here is the 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>
Below is the Javascript login code snippet:
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,
},
}).then(response => {
if (response) {
console.log(response.data);
localStorage.setItem('token', response.data.token);
$state.go('main');
}
}).catch(error => {
console.log(error);
});
};
}
Last but not least, here's the Java Login Handler implementation:
@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());
}
}