【发布时间】:2021-12-21 18:37:59
【问题描述】:
我正在尝试使用 react 和 redux 创建一个简单的登录页面。当我单击登录按钮时,我从两者都收到错误 400(Bad Request)
前端和后端。我正在使用 simplejwt 身份验证。
I have the following as part of the redux action (auth.jsx)
export const login = (email, password) => async dispatch => {
const config = {
headers: {
'Content-Type':'application/json'
}
};
const body = JSON.stringify({email, password});
try{
const res = await axios.post(`${process.env.REACT_APP_API_URL}/user/login`, body, config)
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
})
dispatch(load_user());
} catch (err){
dispatch({
type: LOGIN_FAIL,
})
}
console.log('You hit the wrong url')
}
Redux DevTools 在 try and catch 块中显示 catch `type(pin):"LOGIN_FAIL"`
Login.jsx
const Login = ({ login }) => {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const {email, password} = formData;
const onChange = e => setFormData ({ ...formData, [e.target.name]: e.target.value});
const onSubmit = e => {
e.preventDefault();
login(email, password);
}
return(
<div className='container'>
<Form onSubmit={e => onSubmit(e)}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Control type="email" placeholder="example@email.com" onChange={e => onChange(e)} required />
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Control type="password" placeholder="Password" minLength='6' onChange={e => onChange(e)} required />
</Form.Group>
<Button variant="primary" type="submit">
Login
</Button>
</Form>
</div>
)
// const mapStateToProps = state => ({
// })
}
export default connect(null, {login}) (Login)
登录后台API可以从await axios.post(${process.env.REACT_APP_API_URL}/user/loginpart of the code where看到
REACT_APP_API_URL=http://localhost:8000. The problem now is that when I send a post request by clicking on the submit button to login a user, the content of the form email 和密码does is not passed along because the error on both frontend and backend isPOST http://localhost:8000/user/login 400(错误请求)`
我该如何解决这个问题,或者更确切地说,我做错了什么?
【问题讨论】:
-
由于您使用的是 axios,因此您不需要将其字符串化到正文。您可以直接发送
{ email, password } -
谢谢@LBald。即使没有字符串化错误也是一样的
-
你能从 django 发布后端日志吗?假设您在开发服务器上,原因应该清楚地显示在您运行 django 服务器的控制台中。
-
当然。在 django 控制台中,当我点击登录时显示的是
Bad Request: /user/login [09/Nov/2021 02:42:25] "POST /user/login HTTP/1.1" 400 86 -
似乎最有可能与请求正文结构有关。登录是自定义视图吗?如果是这样,您能否也发布目标 django 视图?
标签: reactjs redux django-rest-framework react-redux axios