I use Axios.
So whenever I use ResponseEntity in Spring Boot to return an error, I can't seem to handle it in my frontend. Instead of getting a proper response from the server, I just get an error that I can't even use.
This is how a positive ResponseEnity is (literally just ResponseEntity.ok(stuff)
):
{data: 'Success', status: 200, statusText: '', headers: {…}, config: {…}, …}
Where I get the actual data I can use, instead of getting this whenever the status code isn't positive ->
This is what I get when I check the console when I send an error ResponseEntity:
xhr.js:210 POST http://{ip}/api/auth/login 403
And I tried to log the error just to see what I get. This is the response:
Error: Request failed with status code 403
at createError (createError.js:16:1)
at settle (settle.js:17:1)
at XMLHttpRequest.onloadend (xhr.js:66:1)
This is how the login processing looks in my backend:
@PostMapping("/login")
public ResponseEntity<?> doLogin(){
/*Imagine it does all the authentication and then throws a 401 error*/
return ResponseEntity
.status(HttpStatus.UNAUTHORIZED)
.body("Error Message");
}
And this is how it's handled in my frontend:
if (request.type === AuthType.LOGIN) {
const { email, password } = request.data;
UserAuthService.login(request.data).then(res => console.log(res));
/*Ideally this is where I'd check for a few HTTP error status codes and act accordingly*/
}
I send the POST request and handle the response. Again, if the code returns 200 OK or any other positive number, then I would be able to use the response data as intended.
Am I missing something?
Just in case here's my Axios instance:
export default axios.create({
baseURL: `${url}`,
headers: {
"Content-type": "application/json",
Authorization: axiosHeader(),
}
});
Which I just import and use whenever I need it.