Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Axios - Upload file to another server

I need to upload a file from a Node.js server to another server using axios. I'm using multer to handle the data received from the client. Here's my code:

const multer = require('multer');
const router = require('express').Router();
const FormData = require('form-data');
const fs = require('fs');

router.post('/profile/:idProfile/post', upload.any(), (req, res) => {
  const file = req.files[0];
  const url = 'https://graph.facebook.com/' + req.params.idProfile + '/photos?access_token=<my-access-token>';
  const fd = new FormData();
  const config = {
    headers: { 'Content-Type': 'multipart/form-data' }
  };

  fd.append('file', fs.createReadStream(file.path), file.path);

  axios.post(url, fd, config)
    .then((res2) => {
      res.send(res2);
    })
    .catch((err) => {
      res.send({
        code: err.response.status,
        error: err.response.data.error
      });
    });
});

I don't see any problems, but I'm still getting the following error from Facebook's Graph API:

{
  "code": 400,
  "error": {
    "message": "(#324) Requires upload file",
    "type": "OAuthException",
    "code": 324,
    "fbtrace_id": "HeA2joMhLQ7"
  }
}

I already tried to upload files directly to the Facebook Graph Api url from a simple html page with success. But I'm not able to understand what's missing here

like image 997
Raphael Avatar asked Jul 22 '26 19:07

Raphael


1 Answers

I found the solution to my problem. I needed to use fd.pipe() and concat to send the image with axios because it's in a binary format:

fd.pipe(concat({ encoding: 'buffer' }, (data) => {
  axios.post(url, data, { headers: fd.getHeaders() });
}));

There's more details on this issue here

like image 82
Raphael Avatar answered Jul 24 '26 12:07

Raphael