Search code examples
node.jsbrowseraxiosfileapi

How to upload file from the back-end to another back-end?


I am trying to upload file from another back-end to currently existing API.

For doing so, I am trying to replicate what's being done in the front-end. To create FormData and then send it to the API.

But the request seems to hang... And if I would try to replicate the request express would console log error

Error: Request aborted
    at IncomingMessage.<anonymous> (C:\Users\TCP_BCP\node_modules\formidable\lib\incoming_form.js:122:19)
    at IncomingMessage.emit (events.js:314:20)
    at IncomingMessage.EventEmitter.emit (domain.js:506:15)
    at abortIncoming (_http_server.js:533:9)
    at socketOnEnd (_http_server.js:549:5)
    at Socket.emit (events.js:326:22)
    at Socket.EventEmitter.emit (domain.js:483:12)
    at endReadableNT (_stream_readable.js:1241:12)

I understand that if I am trying to perform new request the old one gets aborted probably.

But why the request could hang? The target file is small in size (500kb +-).

In the front-end there would be used $(".form").ajaxSubmit

In the back-end I am trying to create form with FormData. enter image description here

What could be wrong?


Solution

  • So the issues was with headers. Formidable at other API would hang without passing FormData headers for axios.

    Code bellow allowed me to successfully upload files to a other API.

          const data = await fs.readFile(zipPath);
          const form = new FormData();
          form.append("file", data, zipName);
          const headers = form.getHeaders();
          Axios.defaults.headers.cookie = cookies;
          await Axios({
            method: "POST",
            url: endpoint,
            headers: {
              ...headers,
              cookie: cookies,
            },
            data: form,
          });