如何使用 TS 在 MERN Stack 项目中发送 FormData

How to send FormData in MERN Stack project with TS

我正在尝试将 FormData 发送到我的后端,但是当我 console.log req.body 它是空对象时,我不知道为什么。

这是我的前端请求:

const createProduct = (e: any) => {
        e.preventDefault();

        const data = new FormData()

        data.append("name", name)
        data.append("description", description)
        data.append("price", price)
        for (const colorAndImage of colorsAndImages) {
            data.append('images', colorAndImage.images[0]);
            data.append('colors', colorAndImage.colors);
        }
        data.append("type", type)

        fetch('http://localhost:4000/products/create', {
            method: 'POST',
            body: data
        }) 

图像文件在控制台中的样子如下:

File {name: 'iphone_13_pro_max_gold_pdp_image_position-1a__wwen_5.jpg', lastModified: 1642862621798, lastModifiedDate: Sat Jan 22 2022 16:43:41 GMT+0200 (Eastern European Standard Time), webkitRelativePath: '', size: 22194, …}

这是我在“网络”选项卡中发送的请求:

name: sdf
description: sdf
price: 234
images: (binary)
colors: red
type: sdf

这是后端的控制器:

productController.post('/create', async (req: Request, res: Response) => {
    console.log(req)
    try {
        const data = req.body;
        let product = await create(data)
        res.status(201).json(product)
    } catch (error) {
        console.log(error);
        //res.status(500).json({error: error})
    }
})

以及当我尝试 console.log 请求时看到的内容:

{
  name: undefined,
  description: undefined,
  price: undefined,
  colors: undefined,
  images: undefined,
  type: undefined,
  likes: undefined
}
Error: Product validation failed: name: Path `name` is required., description: Path `description` is required., price: Path `price` is required., type: Path `type` is required.

我的快速配置:

const corsConfig: cors.CorsOptions = {
    credentials: true,
    origin: ['http://localhost:3000', 'http://localhost:2000']
}

export default function (app: Application) {
    app.use(cors(corsConfig))
    
    app.use(cookieParser());

    app.use(express.urlencoded({ extended: false }));
    app.use(express.json())

    app.use(auth())
}

不确定为什么要使用 FormData 将原始数据从前端发送到后端。

FormData 通常在必须发送(上传)文件时使用。对于简单数据,您只需发送 JSON 对象即可。

Express 默认无法解析 multipart/form-data,您必须安装 multer 等中间件才能获取数据,或者您可以在前端更新数据结构。

let dataToSend = {
  name: name,
  description: description,
  price: price

 // Rest of the properties
}