I'm trying to hook up my react native login with the backend. I use axios ^0.16.2 to call the API, but it always returns me 'Error: Request failed with status code 400' What I have:
export const loginUser = ({ email, password }) => {
return (dispatch) => {
axios.post('http://localhost:8080/api/users/login',
{
email,
password
},
{
Accept: 'application/json',
'Content-Type': 'application/json',
}
)
.then(response => {
console.log(response);
dispatch({
type: LOGIN_USER,
payload: response.data.status
});
Actions.home();
})
.catch(error => {
console.log(error);
dispatch({
type: LOGIN_USER,
payload: error
});
}
);
};
};
Edit: Pretty sure the request body is correct because the database has all the correct info.
I attached the API I have here, I used Java Spring Boot:
@Controller
@RequestMapping(value = "api/users", produces = {MediaType.APPLICATION_JSON_VALUE})
public class UserController {
/**
* Log a user in
* @param request
* @return
* @throws DuplicatedUserException
* @throws InvalidRequestException
*/
public static class UserLoginRequest implements ValiatedRequest {
private String username;
private Integer gmtShift;
private String email;
private String password;
@Override
public void validate() throws InvalidRequestException {
if (email == null || email.isEmpty()) {
throw new InvalidRequestException("email is empty.");
}
if (gmtShift == null || gmtShift < -12 || gmtShift > +12) {
throw new InvalidRequestException("gmtShift is empty or invalid.");
}
if (username == null || username.isEmpty()) {
throw new InvalidRequestException("user name is empty.");
}
if (password == null || password.isEmpty()) {
throw new InvalidRequestException("password is empty.");
}
if (!RegexUtil.EMAIL.matcher(email).find()) {
throw new InvalidRequestException("email is invalid.");
}
if (password.length() > 32) {
throw new InvalidRequestException("password cannot be longer than 32 characters.");
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getGmtShift() {
return gmtShift;
}
public void setGmtShift(Integer gmtShift) {
this.gmtShift = gmtShift;
}
}
@RequestMapping(value = "login", consumes = {MediaType.APPLICATION_JSON_VALUE}, method = RequestMethod.POST)
@ResponseBody
public Response loginUser(
@RequestBody UserLoginRequest request) throws AuthenticationException,
InvalidRequestException {
request.validate();
userService.authenticate(RequestContextHolder.currentRequestAttributes().getSessionId(),
request.getGmtShift(),
request.getUsername(),
request.getEmail(),
request.getPassword());
return new Response(Status.Success);
}
}
}