我有问题,发送到服务器时图片未保存。我通过邮递员检查了我的API是否可以正常工作。在此之前,我成功保存了文章的文本值(标题,描述)。告诉我什么叫纳塔克?谢谢
我的动作//
export const addArticle = (headline, description, image) => {
return (dispatch, getState) => {
console.log('input', headline, description, image); // have image here
// let headers = {"Content-Type": "application/json"};
let headers = {"Content-Type": "multipart/form-data"};
let {token} = getState().auth;
if (token) {
headers["Authorization"] = `Token ${token}`;
}
let formData = new FormData();
formData.append('headline', headline);
formData.append('description', description);
formData.append('image', image, image.name);
// let body = JSON.stringify({headline, description});
return fetch("/api/articles/", {headers, method: "POST", body: formData})
.then(res => {
if (res.status < 500) {
return res.json().then(data => {
return {status: res.status, data};
})
} else {
console.log("Server Error!");
throw res;
}
})
.then(res => {
if (res.status === 201) {
console.log('in fetch', res.data); // no file here
return dispatch({type: ADD_ARTICLE, article: res.data});
} else if (res.status === 401 || res.status === 403) {
dispatch({type: AUTHENTICATION_ERROR, data: res.data});
throw res.data;
}
})
}
};
我的减速机//
export default function articles(state=initialState, action) {
let articleList = state.slice();
...
case ADD_ARTICLE:
articleList.unshift(action.article);
console.log('list', articleList);
return articleList;
...
答案 0 :(得分:0)
正如评论中所写,我发布了适合我的解决方案(可能不太正确):
export const addArticle = (headline, description, image) => {
return (dispatch, getState) => {
let headers = {};
let {token} = getState().auth;
if (token) {
headers["Authorization"] = `Token ${token}`;
}
let formData = new FormData();
formData.append('headline', headline);
formData.append('description', description);
if (image !== null) {
formData.append('image', image, image.name);
}
return fetch("/api/articles/", {headers, method: "POST", body: formData})
.then(res => {
if (res.status < 500) {
return res.json().then(data => {
return {status: res.status, data};
})
} else {
console.log("Server Error!");
throw res;
}
})
.then(res => {
if (res.status === 201) {
return dispatch({type: ADD_ARTICLE, article: res.data});
} else if (res.status === 401 || res.status === 403) {
dispatch({type: AUTHENTICATION_ERROR, data: res.data});
throw res.data;
}
})
}
};