繁体   English   中英

使用 axios 将 FormData 作为参数传递给 post 请求

[英]Passing FormData as parameter to a post request using axios

我试图通过用一些字符串和图片填写表单来上传员工,我正在使用 axios、node.js 来做这件事,但是当我点击提交按钮时,我收到一个错误 (500):

消息员工验证失败:描述:填写员工的描述,姓名:填写员工的姓名。

但我 100% 确定表单已正确填写,我不知道为什么会收到此内部服务器错误。

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

提交:

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

您必须设置"Content-Type": 'multipart/form-data'formDatadata传递formData

例子:

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

在后端,要处理multipart/form-data您需要一个正文解析器(例如 multer)。

Yon 可以在此处阅读更多相关信息。 但是您也可以使用其他一些解析器。

NodeJS 示例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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