在通过 axios 将其发送到我的 Django API 之前,我必须创建一个 fd=new FormData() 对象并使用 [.append()][1] 方法,否则我会收到 400 错误。
在我的后端,个人资料图像通过 OneToOne 关系与用户模型相关联。因此,它被序列化为一个嵌套对象,并期望这个 put 请求能够工作。
对前端状态的所有更改都是通过this.setState 方法完成的。我相信重要的部分是最后的 handleSubmit 方法。
首先我的 axios put 请求:
export const PutUser=(data)=>(dispatch,getState)=>{
dispatch({type: AUTH_USER_LOADING});
const token=getState().auth.token;
axios(
{
¦ method:'put',
¦ url:`https://<xyz>/api/account/user/`,
¦ data:data,
¦ headers:{
¦ ¦ Authorization: 'Token '+token||null,
¦ ¦ 'Content-Type': 'multipart/form-data',
¦ }
})
¦ .then(response=>{
¦ ¦ dispatch({
¦ ¦ ¦ type: AUTH_USER_PUT,
¦ ¦ ¦ payload: response.data,
¦ ¦ });
¦ })
¦ .catch(err=>{
¦ ¦ dispatch({
¦ ¦ ¦ type:AUTH_USER_PUT_ERROR,
¦ ¦ ¦ payload: err,
¦ ¦ });
¦ })
}
我的 handleSubmit 方法需要创建以下 json 对象,其中图像属性被实际用户输入替换:
user:{
username:'charly',
first_name:'charly',
last_name:'brown',
profile:{
image: 'imgurl',
}
}
这是我在组件中的 handleSumit 方法:
检查append
handleSubmit=(e)=>{
¦ e.preventDefault();
¦ let fd=new FormData();
¦ fd.append('username',this.state.username);
¦ fd.append('first_name',this.state.first_name);
¦ fd.append('last_name',this.state.last_name);
¦ if(this.state.image!=null){fd.append('profile.image',this.state.image, this.state.image.name)};
¦ this.props.PutUser(fd);
};