我正在开发一个登录屏幕。我正在使用axios来调用api。 Axios发布请求在使用时返回401错误。但是,当我对要发送的数据进行硬编码时,相同的代码也可以正常工作。它不读取存储在表单中的json格式数据。
我该怎么办?
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)
答案 0 :(得分:0)
对于使用axios发布数据,不需要将数据转换为字符串,只需将其发送出去即可。正确的陈述应为axios.post('http://10.42.0.108:8000/user/login/', values)
代替
axios.post('http://10.42.0.108:8000/user/login/',cred)
----由Navid解答。使用者:3744479