我正在开发一个登录界面。我使用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)
axios.post('http://10.42.0.108:8000/user/login/', values)
而不是axios.post('http://10.42.0.108:8000/user/login/',cred)
。 - undefined