Search code examples
javascriptvue.jsnuxt.jsform-data

FormData() append - Receive only empty objects


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


Solution

  • 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