在Axios上反应登录组件

时间:2019-08-29 10:06:54

标签: reactjs api axios

如何在通过给定会话(通过Jwt)时通过API使React登录组件和重定向到home?

我尝试使用默认的Axios函数,但遇到404错误,尽管可以通过GET来访问API

下面是Login.js

 handleSubmit = input => {
    this.setState({ loading: true });
    input.preventDefault();

    if (this.formisValid(this.state)) {
      this.setState({ errors: [], loading: true });
      axios({
        method: 'POST',
        url: 'http:localhost:3003/api/v1/login',
        data: {
          email    : this.state.email,
          password : this.state.password
        }
      }).then( user => {

        this.setState({ 
          initialState,
          submit: true
        });
        this.setState({ loading: false});
        console.log('User Login', user)

      }).catch((response) => {
        // ? Show to user that request is failed
        this.setState({ errors:[response ]})
        this.setState({ loading: false });
        console.log('request failed', response)
      });
    }
  };

下面是API GET登录结果(通过浏览器)

{"success":false,"data":{"error":"Body cannot be empty"}}

预期结果是登录成功后(可以通过Jwt进行会话)将用户定向到首页(/)

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

你可以试试吗?

axios.post('http://localhost:3003/api/v1/login', {
      email    : this.state.email,
      password : this.state.password
    })
  .then(user => {
    /* */
  })