reactjs - 从 React 向 Django 发送 post 请求时出现 400(错误请求)
问题描述
我正在尝试使用 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/login part 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 and password does is not passed along because the error on both frontend and backend is
POST http://localhost:8000/user/login 400 (Bad Request)`我该如何解决这个问题,或者更确切地说,我做错了什么?
解决方案
登录 URL 错误使用基于令牌的身份验证应该是http://localhost:8000/rest-auth/login/ 。你需要休息框架。
推荐阅读
- python - 多处理池生成初始化非常慢,16 个进程为 100 秒
- ruby-on-rails - Ruby on rails.Generating 控制器
- azure-cosmosdb - 为处理夜间大查询和大数据的单个容器设计 Cosmos 分区键
- c++ - C++20 行为用相等运算符破坏现有代码?
- base64 - 市政府公共记录请求中电子邮件的 Base64 编码附件
- android - Android:Activity 中的 Jetpack Compose 和 XML
- dart - Dart Future 异步未按预期工作
- python - 如何更快地生成单词表?
- docker - docker inspect - 将其输出格式化为表格
- leaflet - Leaflet.JS 标记在对面地图上的坐标上