Rvfvl
Rvfvl

Reputation: 383

Uploading file from my server API to another API - Node JS (Express)

I have a client-side API request that should send a POST request to my own express server with a formData file that should be then accessed in my server route and pass it forward to the third party API.

const addAttachment = async () => {
  const formData = new FormData();
  formData.append("file", fileInput.files[0]);

  const result = await axios.post("http://my-server:5000/attachment", formData);

  console.log(result);
};

Then on my server side I am accessing this route:

app.post("/attachment", multer().single("file"), async (req, res) => {
  console.log(req.file);

  fetch("http://expternal-api.com/rest/api/attachments", {
    method: "POST",
    body: req.file,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  })
    .then((res) => console.log(res))
    .then((result) => res.json(result))
    .catch((err) => console.log(err));
});

I am using multer to access file from my browser request to the server and the output of this req.file is:

{
  fieldname: 'file',
  originalname: 'New Text Document (2).txt',
  encoding: '7bit',
  mimetype: 'text/plain',
  buffer: <Buffer 74 65 73 74 73 65 74 65 73 74 73 74 65 74>,
  size: 14
}

But the problem is whether this is correct because in my console.log from the server I am keep getting error 500 Internal server error. Am I passing correct body to the third party API? It should use multipart/form-data, but I am not sure whether Multer somehow changes my output so it causes an error.

Upvotes: 0

Views: 2329

Answers (1)

Phil
Phil

Reputation: 164897

You'd need to construct a new FormData instance in your Express server and append the file.

Install form-data and try this...

const fetch = require("node-fetch") // or whatever you already have
const FormData = require("form-data")
const fs = require('fs') // required if using Multer DiskStorage, see below

app.post("/attachment", multer().single("file"), async (req, res) => {
  console.log(req.file);

  const fd = new FormData()

  // looks like you're using MemoryStorage, so use
  fd.append("file", req.file.buffer) // "file" is the fieldname expected by the API

  // when using Multer DiskStorage, use
  // fd.append("file", fs.createReadStream(req.file.path));

  try {
    const response = await fetch("http://expternal-api.com/rest/api/attachments", {
      method: "POST",
      body: fd,
      headers: {
        fd.getHeaders()
      },
    })

    if (!response.ok) {
      throw new Error(`${response.status}: ${await response.text()}`)
    }

    const result = await response.json()
    res.json(result) // ¯\_(ツ)_/¯
  } catch (err) {
    console.error(err)
    res.status(500).send(err)
  }
});

Upvotes: 2

Related Questions