0

目前,我的代码正在与我的 django-rest-auth api 通信。它正在获取令牌,但是,它没有对请求进行身份验证。我的后端显示 200(用户名和密码正确)。当我的前端,reactjs 声明错误的用户名或密码(我在 else 语句中创建)和 400 错误请求错误。

 axios
      .post(
          'http://127.0.0.1:8000/rest-auth/login/',
          {
                username: this.state.username,
                password: this.state.password
          },
        //   { withCredentials: true }
          { isAuthenticated: true }
      )
          .then(response => {
              const token = response.data.key;
              if (localStorage.getItem(token)) {
                  console.log(token);
                  this.props.handleSucessfulAuth();
              } else {
                  this.setState({
                      errorMessage: 'Wrong username or password'
                  });
                  this.props.handleUnsuccessfulAuth();
                //   console.log(token);
              }

          })

       .catch(error => {
           this.setState({
               errorMessage: 'Authorization error occured',
               error
           })
           this.props.handleUnsuccessfulAuth();
    });

}

现在我已将顶部更改为以下内容:

handleSubmit(event) {
        event.preventDefault();
        axios.defaults.headers.common["Authorization"] = `Token ${this.props.token}`;

        axios
          .post(
              'http://127.0.0.1:8000/rest-auth/login/',
              {
                    username: this.state.username,
                    password: this.state.password
              },
            //   { withCredentials: true }
              { isAuthenticated: true }
          )
              .then(response => {
                  const token = response.data.key;
                  if (localStorage.setItem(token, 'token')) {
                      console.log(token);
                      this.props.handleSucessfulAuth();
                  } else {
                      this.setState({
                          errorMessage: 'Wrong username or password'
                      });
                      this.props.handleUnsuccessfulAuth();
                    //   console.log(token);
                  }

              })
4

0 回答 0