簡體   English   中英

Postman 可以將文件上傳到節點 api。 但不適用於 React

[英]Postman can upload file to a Node api. But Not with React

Redux代碼

export const uploadImage = data => async dispatch => {
    const config = {
        headers: {
            "Content-Type": "multipart/form-data"
        }
    };

    try {
        const res = await axios.post("/api/profile/upload", data, config);
        // const res = await axios.post("/api/profile/upload", data, {
        //  headers: {
        //      "Content-Type": "multipart/form-data"
        //  }
        // });
        console.log(res);
        dispatch({
            type: AVATAR_UPLOAD,
            payload: res.data
        });
    } catch (err) {
        const errors = err.response.data.errors;

        if (errors) {
            errors.forEach(error => dispatch(setAlert(error.msg, "danger")));
        }

        dispatch({
            type: PROFILE_ERROR,
            payload: { msg: err.response.statusText, status: err.response.status }
        });
    }
};

反應代碼

const data = new FormData();
data.append("file", avatar);
uploadImage(data);

我收到錯誤的請求消息,req.files 為空我嘗試使用 Postman 相同的配置上傳文件,似乎 api 有效,但無法使用 react formdata 上傳。

任何想法將不勝感激。 提前致謝

嘗試這樣做:

const formData = new FormData();
formData.append('file', file);
const res = await axios.post("/api/profile/upload", formData, config);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM