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

6
  • Hi, are you aware about this? Also, what do you see in your network tab (from the frontend to the backend)? Commented Sep 21, 2022 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 Commented Sep 21, 2022 at 17:43
  • The client side code looks fine. It's on the backend side. Do you have those middlewares? stackoverflow.com/a/4296402/8816585 Commented Sep 21, 2022 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 Commented Sep 21, 2022 at 18:00
  • Double check your version and try with it to be sure. Commented Sep 21, 2022 at 18:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.