首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React Native axios总是返回“请求失败,状态代码为400”

React Native axios总是返回“请求失败,状态代码为400”
EN

Stack Overflow用户
提问于 2017-09-16 06:33:44
回答 2查看 10K关注 0票数 2

我正在尝试将我的react原生登录与后端连接起来。我使用axios^0.16.2来调用API,但它总是返回“Error: Request failed with status Code400”,如下所示:

代码语言:javascript
复制
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:

代码语言:javascript
复制
@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);
    }
}
}
EN

回答 2

Stack Overflow用户

发布于 2018-02-15 13:51:50

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

代码语言:javascript
复制
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);
  });
票数 3
EN

Stack Overflow用户

发布于 2018-03-30 17:56:28

这样啊,原来是这么回事!

  1. 导入此代码:

代码语言:javascript
复制
axios.post(Uri,Qs.stringify(data))
  .then(function(result){})
  .catch(function(error){});

  1. ,因为你的API通过" @RequestBody""@RequestParam"!

获得了para。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46248255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档