1

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)
    }
}

1 Answer 1

2

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
});
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.