【问题标题】:React Native axios always returns 'Request failed with status code 400'React Native axios 总是返回“请求失败,状态码 400”
【发布时间】:2018-02-25 03:48:28
【问题描述】:

我正在尝试将我的 react 本机登录与后端连接起来。我使用 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);
    }
}
}

【问题讨论】:

  • 可能和你的api有关。也请从您的 api 中添加相关代码。
  • 您确定信息已正确发送到 API 吗?发布完整的请求信息,您可以通过使用 React Native Debugger 或 Chrome Inspector 检查 JS,然后在 Network 选项卡中单击所需的请求来获取它。
  • 尝试使用 Postman 检查 API 是否按预期返回结果,然后添加一些 console.logs 来调试 API 或您的 axios。 getpostman.com
  • 是的。我确实在邮递员上测试过,一切正常。它只是在本机反应中不起作用。我对这里发生的事情感到非常困惑......
  • 尝试设置内容类型,如 axios.defaults.headers.post['Content-Type'] = 'application/json' 看看是否有变化......也分享你的邮递员测试

标签: post react-native redux request axios


【解决方案1】:

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

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】:

    我明白了!

    1. 导入qs.js;
    2. 使用此代码:
    axios.post(Uri,Qs.stringify(data))
      .then(function(result){})
      .catch(function(error){});
    
    1. 因为您的 API 被 " @RequestBody""@RequestParam" 获取参数!

    【讨论】:

    • 为什么我们需要Qs才能使用axios?毫无意义,这是必需的......我今天遇到了同样的错误,我的代码昨天工作正常
    猜你喜欢
    • 2019-09-29
    • 2020-04-05
    • 2021-01-12
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2020-04-25
    • 2017-06-02
    相关资源
    最近更新 更多