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}
In
fileUploadController.jsyou're usingfs's APIs incorrectly.fs.readFiletakes a callback; it does not return your file. Your code should look somewhat like this: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.readFileSyncor the promise version.Besides that, as pointed out in the comments, axios returns a promise, so you should be awaiting it (also notice the
asyncpreceding the current function declaration).