post - React Native axios总是返回 'Request failed with status code 400'

标签 post react-native redux request axios

我正在尝试将我的 react native 登录与后端连接起来。我使用 axios ^0.16.2 调用 API,但它总是返回“错误:请求失败,状态代码为 400” 我有什么:

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
                                });
                        }
                );
        };
};

编辑: 非常确定请求正文是正确的,因为数据库具有所有正确的信息。

我在这里附上了我的API,我使用了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);
    }
}
}

最佳答案

您可能没有以正确的方式发送请求。我也遇到了同样的错误,但我设法解决了这个问题。 我正在添加我的代码,希望这会对某人有所帮助。

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);
  });

关于post - React Native axios总是返回 'Request failed with status code 400',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248255/

相关文章:

react-native - ReactNative [Flatlist]scrollToOffset,如何计算出单击行的偏移位置?

javascript - 元素类型无效 : expected a string (for built-in components) or a class/function (for composite components) but got: object. React-Native

php - 请求格式错误时如何获取原始请求数据?

c# - 使用 SOAP,如何在一个请求中传递多个 ID?

javascript - 找不到入口文件 index.js - React Native

reactjs - 如何使用重新选择和 typescript 创建自定义相等函数?

reactjs - 使用 Redux 响应热重载

c# - 如何通过 POST 将参数传递到 Azure Functions 2

asp.net-mvc - 授权属性不保留发布数据

javascript - 具有值的 React textarea 是只读的,但需要更新