When it comes to fetching APIs created on the backend, I encounter some challenges. While handling everything correctly on the front-end server side, issues arise with error handling as the catch(error) method only captures errors originating from the front-end rather than the back-end. My tech stack mainly revolves around VueJS and Spring Boot. Let me provide an example to better illustrate my situation.
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getEmail(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getEmail(),
roles));
}
On the front-end side, I simply consume this API by creating a service in VueJS that is invoked upon a button click within one of my views. Here's how my service looks:
class AuthService{
login(user){
return fetch("http://localhost:100/api/v1/auth/signin",
{method : "POST",
headers:{
"Content-type" : "application/json"
},
body: JSON.stringify({
email:user.email,
password: user.password,
}),
}).then( response => response.json()).then(data =>{
if (data.accessToken){
localStorage.setItem('user',JSON.stringify(data))
}
return data})
}
logout(){
localStorage.removeItem('user')
}
}
export default new AuthService();
This service is connected to my module (Vuex) in the localstore:
import AuthService from '../services/auth.service';
const user = JSON.parse(localStorage.getItem('user'));
const initialState = user
? { status: { loggedIn: true }, user }
: { status: { loggedIn: false }, user: null };
export const auth = {
namespaced: true,
state: initialState,
actions: {
// relevant action methods here
},
mutations: {
// relevant mutation methods here
}
};
Lastly, there is a view responsible for triggering the actions - it comprises a form with input fields that are sent to the backend via a post method call. The LoginForm.vue file has the following content:
<template>
<div id="nav">
<!-- components -->
</div>
</template>
<script>
//script content
</script>
In conclusion, while I am able to handle errors effectively, I am unsure if my approach aligns with conventional practices. For instance, should I rely on if statements to manage errors from the backend or explore alternative methodologies? Any insights on securing my system would be greatly appreciated.
Form Screenshot