Axios的POST请求返回401未授权错误

3

我正在开发一个登录界面。我使用axios调用api。当使用Axios post请求时,会返回401错误。但是当我硬编码要发送的数据时,相同的代码运行良好。它无法读取存储在表单中的json格式数据。
我该怎么办?

最初的回答:

您可能需要检查您的代码是否正确地从表单中获取数据并将其转换为JSON格式。您还可以尝试在Axios post请求中添加身份验证标头。

class Login extends React.Component {
      handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
          if (!err) {
            let cred= JSON.stringify(values);
            console.log('json values of form: ',cred );
            axios.post('http://10.42.0.108:8000/user/login/',cred)
            .then(function (response) {
              console.log(response);
            });
            // .catch(function (error) {
            //   console.log(error);
            // });
          }
        });
      };

      render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <React.Fragment>
              <div className='login'>
    <div className="login-container shadow-lg p-3 mb-5 ml-3 bg-white rounded">               
        <Form onSubmit={this.handleSubmit} className="login-form px-5 py-5">
            <div className="text-center">
                    <h3 className="dark-grey-text mb-5">
                      <strong>Sign in</strong>
                    </h3>
            </div>
            <Form.Item>
              {getFieldDecorator('outlook_id', {
                rules: [{ required: true, message: 'Please input your username!' }],
              })(
                <Input
                  prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  placeholder="Username" style={{width:'300px'}}
                />,
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: 'Please input your Password!' }],
              })(
                <Input
                  prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                  type="password"
                  placeholder="Password" style={{width:'300px'}}
                />,
              )}
            </Form.Item>
            <Form.Item>
              {/* {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: true,
              })(<Checkbox>Remember me</Checkbox>)} */}

              <Button type="primary" htmlType="submit" className="login-form-button">
                Log in
              </Button>
            </Form.Item>
          </Form>
      </div>
         </div>
         </React.Fragment>    
        );
      }
    }

const WrappedLogin = Form.create({ name: 'normal_login' })(Login);
export default WrappedLogin;

我尝试更改变量等一切,但它总是返回相同的错误。我对此不太熟悉,请帮忙解决。以下是该错误信息。

最初的回答:

POST http://10.42.0.108:8000/user/login/ 401 (Unauthorized)
Uncaught (in promise) Error: Request failed with status code 401
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

为什么要将你的 JSON 序列化成字符串呢?你的后端接收到的是字符串还是 JSON 数据?如果需要传送 JSON,只需直接发送原始对象即可。 - undefined
后端需要以JSON格式的数据。 - undefined
@Wijitha 是的,这些值看起来确实是精确的。 - undefined
表单的JSON值为: {"outlook_id":"aashik1","password":"ascascsdc"} 这是我在控制台上得到的结果。 - undefined
1
@ArunKAnil 发送数据使用axios时,无需将数据转换为字符串,只需直接发送即可。正确的语句应该是 axios.post('http://10.42.0.108:8000/user/login/', values) 而不是 axios.post('http://10.42.0.108:8000/user/login/',cred) - undefined
显示剩余3条评论
1个回答

2

使用axios发布数据时不需要将数据转换为字符串,只需直接发送即可。正确的语句应该是axios.post('http://10.42.0.108:8000/user/login/', values),而不是

axios.post('http://10.42.0.108:8000/user/login/', JSON.stringify(values))

axios.post('http://10.42.0.108:8000/user/login/',cred)

----由Navid回答。用户:3744479

最初的回答


1
谢谢!所以如果你想添加身份验证令牌,应该使用axios.post('http://10.42.0.108:8000/user/login/',cred,head),将令牌作为第三个参数,不像GET请求那样。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接