首页 > 解决方案 > Axios 上的 React 登录组件

问题描述

如何通过 API 制作 React 登录组件并在提供会话时重定向到主页(通过 Jwt)?

我尝试使用默认的 Axios 功能,但遇到 404 错误,而 API 可以通过 GET 访问

下面是 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 进行会话)

谢谢你的帮助

标签: reactjsapiaxios

解决方案


你能试试这个吗?

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

推荐阅读