0

I started a new project and had never issues to append data to FormData and sending it to the backend. Currently, I receive only empty objects in the backend. What am I missing here?

this.first_name is not empty if I console.log it. That's not the problem here.

async createAgent() {
      const data = new FormData()
      data.append('first_name', this.first_name)
      // data.append('last_name', this.last_name)
      // data.append('phone', this.phone)
      // data.append('email', this.email)
      // data.append('languages', this.checkedLanguage)
      // data.append('image', this.selectedFile)

      try {
        const post = await this.$axios.$post('/api/create-agent', data)
    }

Node.js

exports.createAgent = async (req, res) => {
  console.log(req.body.first_name);
  console.log(req.body);
};

Console Output

undefined
{}

index.js (Node.js)

const app = express();

app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Headers

Payload

PhilippeUn
  • 190
  • 2
  • 16
  • Hi, are you aware [about this](https://developer.mozilla.org/en-US/docs/Web/API/console/log#logging_objects)? Also, what do you see in your network tab (from the frontend to the backend)? – kissu Sep 21 '22 at 17:26
  • Hi Kissu, I've read about it, but even then I get an empty answer. Or when I want to save the data in the database, nothing arrives there. I don't notice anything unusual in the Network tab. But I am not a pro :-) I added some images – PhilippeUn Sep 21 '22 at 17:43
  • The client side code looks fine. It's on the backend side. Do you have those middlewares? https://stackoverflow.com/a/4296402/8816585 – kissu Sep 21 '22 at 17:47
  • Yes, I'm using express with bodyparser. But I see since express v4.16.0, you don't have to use bodyparser? Currently, I'm using express v4.18.1 – PhilippeUn Sep 21 '22 at 18:00
  • Double check your version and try with it to be sure. – kissu Sep 21 '22 at 18:01
  • I tried it without bodyParser ... and ... with express downgrading + bodyparser. Both didn't work :-( – PhilippeUn Sep 21 '22 at 18:14

1 Answers1

2

According to body-parser's docs:

This does not handle multipart bodies, due to their complex and typically large nature.

which in your screenshot, on the Request Headers part, is stated.

Solutions in your example are:

  • just send a JSON payload (parsed by bodyParser.json())
  • set Content-Type to application/x-www-form-urlencoded (parsed by bodyParser.urlencoded())
  • use the recommended modules for multipart body in the docs:

Docs: https://github.com/expressjs/body-parser/tree/1.20.0#readme

To send a JSON payload with axios which you are using in the OP, do:

axios.post({
  first_name: "This is a JSON property"
})

or

$axios.$post()

which IF you're using nuxt/axios, is a convenient function that will return the response body instead of the whole response.

Docs: https://axios.nuxtjs.org/usage#-shortcuts

captainskippah
  • 1,350
  • 8
  • 16