简体   繁体   中英

Passing FormData as parameter to a post request using axios

I'm trying to upload an employee by filling a form with some strings and a picture, I'm using axios, node.js to do it, but when I hit the submit button I get an error (500):

message Employees validation failed: description: fill the employee's description, name: fill the employee's name.

but I'm 100% sure that the form was filled correctly and I don't have a clue why I'm getting this internal server error.

export const createEmployee = async (formData) => {
    try {
      const url = `${Constants.BASE_URL}/employee`
      const res = await axios({
        method: 'post',
        url,
        data:formData,
        headers: {
        "Content-Type": 'multipart/form-data'
        }
      });

      if (res.data.status === 'success') {
        showAlert('success', `${res.data.name} Cadastro realizado com sucesso!`);
        window.location = '/employee';
      }
    } catch (err) {
      showAlert('error', err.response.data.message);
    }
  };

Submit:

const employeeCreateDataForm = document.querySelector('#createEmployeeForm');
if (employeeCreateDataForm)
  employeeCreateDataForm.addEventListener('submit', e => {
    e.preventDefault();
    const form = new FormData();
    form.append('name', document.getElementById('name').value);
    form.append('photo', document.getElementById('photo').files[0]);
    form.append('phone', document.getElementById('phone').value);
    form.append('description', document.getElementById('description').value);

    createEmployee(form);
});

You have to set the header of "Content-Type": 'multipart/form-data' and pass the formData in data .

Example:

export const createEmployee = async (formData) => {
  try {
    const url = `${Constants.BASE_URL}/employee`
    const res = await axios({
      method: 'post',
      url,
      data: formData,
      headers: {
        "Content-Type": 'multipart/form-data'
      }
    });
    if (res.data.status === 'success') {
      showAlert('success', `${res.data.name} Cadastro realizado com sucesso!`);
      window.location = '/employee';
    }
  } catch (err) {
    showAlert('error', err.response.data.message);
  }
};

On backend side, To handle the multipart/form-data you need a body parser (such as multer).

Yon can read more about this here . But you could use some other parser as well.

NodeJS Example:

const express = require("express");
const cors = require("cors");
const multer  = require('multer');

const app = express();
const upload = multer();

app.use(cors());
app.post("/employee", upload.single('photo'), (req, res) => {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
});
app.listen(5000, () => {
    console.log(`Server is running on port 5000`);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM