I am sending a form data from reactjs app using axios, described in the code below. The express is configured properly and still the req.body
is empty. What am I doing wrong in this case?
import bodyParser from 'body-parser';
app.use(busboy());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
reactjs
export const createAd = (token, ad) => async (dispatch) => {
const headers = {
headers: {
"content-type": "multipart/form-data",
Authorization: `Bearer ${token}`,
},
};
for (var pair of ad.entries()) {
console.log(pair[0] ', ' pair[1]);
}
const response = await api
.post("/ads/create/", ad, headers)
.catch((error) => {
dispatch({ type: constants.PUSH_ERROR, payload: error });
});
if (response && response.status === 201) {
dispatch({ type: constants.CREATE_AD, payload: response.data.ad });
}
};
api endpoint
export const createAd = async (req, res) => {
try {
const bb = busboy({ headers: req.headers });
bb.on('file', async (name, file, info) => {
console.log("*Uploading files")
const { filename, encoding, mimeType } = info;
var saveTo = 'public/ads/' filename
file.pipe(fs.createWriteStream(saveTo));
file.resume();
});
bb.on('finish', () => {
console.log('Upload complete');
res.writeHead(200, { 'Connection': 'close' });
res.end("That's all folks!");
});
console.log(req.body) // empty body here {}
res.status(201).send({ message: "Ad created.", ad: {} });
} catch (error) {
res.status(400).send(error)
console.error(error)
}
}
CodePudding user response:
Using multiparty library you can also do this.
app.post('/ads/create/', function (req, res) {
var form_data = new multiparty.Form();
form_data.parse(req, function(err, fields, files) {
// fields fields fields
});
})