我正在嘗試將 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())
}
uj5u.com熱心網友回復:
不知道為什么要使用 FormData 將原始資料從前端發送到后端。
當您必須發送(上傳)檔案時,通常使用 FormData。對于簡單資料,您可以發送 JSON 物件。
Express 默認無法決議multipart/form-data,您必須安裝像multer這樣的中間件才能獲取資料,或者您可以在前端更新資料結構。
let dataToSend = {
name: name,
description: description,
price: price
// Rest of the properties
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438879.html
上一篇:為什么在MongoDBupdateOne中使用slice不會從陣列中洗掉一個專案,而只會用一個奇怪的物件替換它?
