首页 > 解决方案 > 为什么当我将 React 表单设置为 multipart/form-data 时,它会被视为 application/json?我上传的文件被视为未定义

问题描述

我正在尝试将带有 React 的图像文件上传到我的 NodeJS 后端,但该文件似乎没有作为 multipart/form-data 进行处理。我已将表单设置为“multipart/form-data”,但每次将其发送到后端时,它都会被读取为“application/json”。

用表单反应组件:

import axios from 'axios';
import React, { useContext, useState, useRef} from 'react';
import CollectionAPI from "../apis/collectionAPI";
import {CollectionContext} from '../context/collectionContext';

const AdminCreateC = (props) => {

    const{createItem, setCreateItem} = useContext(CollectionContext);

    const [images, setImages] = useState(null);

    //insures that the .env file is only run in a development environment and not a production environment
    if(process.env.NODE_ENV !== 'production'){
        //requires the the .env file configuration be run first hiding all info hidden via the .env file
        require('dotenv').config();
    }

    const handleSubmit = async (e) => {
        e.preventDefault()
        try{

            let formData = new FormData();
            formData.append('images', images);

            console.log(formData)
            axios.post("https://httpbin.org/anything", formData).then(res => console.log(res));

            const response = await CollectionAPI.post("/admin/create", {
                images: formData,
            })

            setCreateItem(response.data.data.newItem);

        }catch(err){
            console.log(err);
        }
    }

    return(
        <div>
             {/* The form enctype is set to multipart/form-data*/}
             <form action="/admin/create" method="POST" encType="multipart/form-data">
                  <div className="admin-form">
                       <label className="">Images</label>
                       <input  type="file" onChange={e => setImages(e.target.files[0])} name="images" className="form-control" required/>
                  </div>
             </form>
        </div>
    )
}

export default AdminCreateC;

NodeJS Route:(req.file 似乎总是未定义)

//Create a collection item
router.post('/admin/create', upload.single('images'), async(req, res) => {
    try{
        const file = req.file;
        console.log("File: " + file);
    }catch(err){
        console.log(err);
    }
})

标签: node.jsreactjsexpressmulter

解决方案


Axiospost方法的默认Content-Type值为'application/x-www-form-urlencoded'.

您需要将其更改为multipart/form-data

axios.post(
  "https://httpbin.org/anything", 
  formData, 
  {
    headers: {
      "Content-Type": "multipart/form-data"
    }
  })
  .then(res => console.log(res)
);

推荐阅读