2
votes

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);
    }
}
}
2
Might be related to your api. Please add related code from your api too.bennygenel
Are you sure the information is being correctly sent to the API? Post the full request information, you can get it by inspecting the JS using React Native Debugger or Chrome Inspector, and then clicking in the desired request in the Network tab.Luís Brito
Try using Postman to check if the API is returning the result as expected, then add some console.logs to debug either the API or your axios. getpostman.comsoutot
yea. I did test it on postman and all works fine. It just does not work in react native. Im so confused about whats going on here...frogLuan
try setting content-type like axios.defaults.headers.post['Content-Type'] = 'application/json' and see if something is changed... Also share your postman test as wellPanagiotis Vrs

2 Answers

3
votes

It may be possible that you are not sending the request in a proper way. I was also getting the same error, but some how I managed to fix the issue. I am adding my code, hope this will help someone.

axios.post('Api Url',
  {
      'firstName': firstNameValue,
      'lastName': lastNameValue,
      'stateId': stateValue,
      'email': emailValue,
      'password': passwordValue,
      'deviceInfo': deviceInfo 
  },{
      "headers": {
        'Content-Type': 'application/json',
      }
  }).then((response) => {
     console.log("reactNativeDemo","response get details:"+response.data);
  })
  .catch((error) => {
     console.log("axios error:",error);
  });
2
votes

I got it!

  1. import qs.js;
  2. with this code:
axios.post(Uri,Qs.stringify(data))
  .then(function(result){})
  .catch(function(error){});
  1. Because your API get para by " @RequestBody" or "@RequestParam"!