Не удается POST файл для экспресс-конечной точки с Axios через React - PullRequest
0 голосов
/ 29 августа 2018

Я в полном тупике. Я искал ТАК за ответы, часами, и, кажется, не могу заставить что-либо работать.

  • Реагировать приложение

  • Аксиосы ​​для AJAX

  • Попытка отправки файла в конечную точку Express с помощью multer.

Моя конечная точка:

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });


router.post("/", upload.single("file"), async (req, res) => {
    let file = req.file.buffer; //...file is undefined from Axios, has buffer from Postman and works
    //...etc...
});

Моя форма:

onChangeFile = e => {
    let file = e.target.files[0];
    let formData = new FormData();
    formData.append("file", formData);
    const reqParams = {
        method: "POST",
        url: `https://myapi.com/documents`,
        data: {
            "file": formData
        },
        headers: {
            "my_custom_header": "ABC123"
        }
    };
    axios(reqParams)
        .then(result => console.log(JSON.stringify(result, null, 4)))
        .catch(e => console.log(e));
}

render() {
    <form encType="multipart/form-data">
        <input type="file" name="file" id="file" onChange={this.onChangeFile} />
    </form>
}

Результат результата Axios сверху:

{
    "data": [
        {
            "source": "system",
            "type": "json",
            "status": 200,
            "reason": null,
            "message": "Successful",
            "error": false,
            "date": "2018-08-28T21:35:36.000Z",
            "payload": {
                "my_custom_header": "ABC123",
                "file": {}
            }
        }
    ],
    "status": 200,
    "statusText": "OK",
    "headers": {
        "content-type": "application/json; charset=utf-8"
    },
    "config": {
        "transformRequest": {},
        "transformResponse": {},
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8",
            "my_custom_header": "ABC123"
        },
        "method": "post",
        "url": "https://myapi.com/documents",
        "data": "{\"file\":{}}"
    },
    "request": {}
}

Конечная точка прекрасно работает с почтальоном. Я следовал этой статье, изначально: https://blog.stvmlbrn.com/2017/12/17/upload-files-using-react-to-node-express-server.html

...