How to send a file via axios to an external api using node js

837 Views Asked by At

I am new to node js and i am developing the server-side of my nuxt project. actually i want to send a file to an external api but i get error Callback must be a function

in my server.js

let formidable = require('formidable');
const bodyParser = require('body-parser')
const app = require('express')()
const cookieParser = require('cookie-parser')
var fs = require('fs');
const cors = require('cors');

const fileUploadController = require("./controllers/fileUploadController");
app.use('/uploads', fileUploadController.uploadFile)

in my fileUploadController.js

function uploadFile(req, res, next) {
   const axios = require('axios');
   const FormData = require('form-data');
   const fs = require('fs');

   const image =  fs.readFile('./down.png');

   const form = new FormData();
   form.append('productName', 'Node.js Stickers');
   form.append('productDescription', 'Cool collection of Node.js stickers for your laptop.');
    form.append('productImage', image, 'down.png');

   const response =  axios.post('http://api.com/api/nuxt', form, {
    headers: 
    {
     'Content-Type': 'multipart/form-data',
     }  
   });
 }

 module.exports = {uploadFile} 
1

There are 1 best solutions below

2
code On

In fileUploadController.js you're using fs's APIs incorrectly. fs.readFile takes a callback; it does not return your file. Your code should look somewhat like this:

// fileUploadController.js
function uploadFile(req, res, next) {
  const axios = require('axios');
  const FormData = require('form-data');
  const fs = require('fs');

  fs.readFile('./down.png', async function(err, image) => {

    const form = new FormData();
    form.append('productName', 'Node.js Stickers');
    form.append('productDescription', 'Cool collection of Node.js stickers for your laptop.');
    form.append('productImage', image, 'down.png');

    const response = await axios.post('http://api.com/api/nuxt', form, {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    });
  });
}

module.exports = {
  uploadFile
};

The reason this takes a callback is because JavaScript is asynchronous and doesn't wait for fs to finish reading the file before moving on, so you have to give the function something to execute once it's finished.

I wouldn't personally use callbacks though; you could use fs.readFileSync or the promise version.

Besides that, as pointed out in the comments, axios returns a promise, so you should be awaiting it (also notice the async preceding the current function declaration).