我使用 Multer 将图像上传到数据库并将其保存在名为“uploads”的文件夹中。但是当我在 Thunder 客户端上测试它时,它显示代码“req..file”未定义。这是 FoodRoutes 代码:
import express from "express"
import { addFood } from "../controller/foodController.js"
import multer from "multer"
const foodRouter = express.Router()
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads")
},
filename: function (req, file, cb) {
cb(null, `${Date.now()} + "-" + ${file.originalname}`)
}
})
const upload = multer({storage:storage})
foodRouter.post("/add", upload.single("image"),addFood)
export default foodRouter;
控制器:
import foodModel from "../models/foodsModel.js";
import fs from 'fs'
// add food item
const addFood = async (req,res) => {
let image_filename = `${req.file.filename}`
const food = new foodModel({
name: req.body.name,
description: req.body.description,
price: req.body.price,
category: req.body.category,
image: image_filename
})
try {
await food.save();
res.json({success:true, message: "Thêm món ăn thành công"})
} catch (error) {
res.status(500).json({success:false, message: "Lỗi khi thêm món ăn", error})
}
}
export {addFood}
错误说:
file:///C:/Users/kienk/OneDrive/Desktop/Nh%C3%A1p/BanDoAn/server/controller/foodController.js:8
let image_filename = `${req.file.filename}`
^
TypeError: Cannot read properties of undefined (reading 'filename')
at addFood (file:///C:/Users/kienk/OneDrive/Desktop/Nh%C3%A1p/BanDoAn/server/controller/foodController.js:8:38)
at Layer.handle [as handle_request] (C:\Users\kienk\OneDrive\Desktop\Nháp\BanDoAn\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\kienk\OneDrive\Desktop\Nháp\BanDoAn\server\node_modules\express\lib\router\route.js:149:13)
at done (C:\Users\kienk\OneDrive\Desktop\Nháp\BanDoAn\server\node_modules\multer\lib\make-middleware.js:45:7)
at indicateDone (C:\Users\kienk\OneDrive\Desktop\Nháp\BanDoAn\server\node_modules\multer\lib\make-middleware.js:49:68)
at Multipart.<anonymous> (C:\Users\kienk\OneDrive\Desktop\Nháp\BanDoAn\server\node_modules\multer\lib\make-middleware.js:166:7)
at Multipart.emit (node:events:519:28)
at emitCloseNT (node:internal/streams/destroy:147:10)
at process.processTicksAndRejections (node:internal/process/task_queues:81:21)
Node.js v20.17.0
[nodemon] app crashed - waiting for file changes before starting...
我要求AI修复,但它无法解决任何问题。我该怎么办=(??
您的后端代码已设置好。 测试数据中遗漏了一些东西。 这就是您现在收到错误的原因。
我已经测试了您的后端代码,如下所示。这里我使用相同的后端代码来发出测试发布请求。并且成功将测试文件上传到服务器。文件将上传到名为 upload 的文件夹中。
服务器.js
const express = require('express');
const app = express();
const foodRouter = require('./foodRouter.js');
app.use('/', foodRouter);
const body = new FormData();
body.set('image', new Blob(['some image'])); // some blob/file content
body.set('name', 'somename'); // some text input
app.listen(3000, () => {
console.log('L@3000');
fetch('http://localhost:3000/add', {
method: 'POST',
body,
})
.then((response) => {
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
return response.text();
})
.then((json) => console.log(json))
.catch((error) => console.log(error));
});
foodRouter.js
const express = require('express');
const multer = require('multer');
const foodRouter = express.Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads');
},
filename: function (req, file, cb) {
cb(null, `${Date.now()} + "-" + ${file.originalname}`);
},
});
const upload = multer({ storage: storage });
const addFood = async (req, res) => {
let image_filename = `${req.file.filename}`;
res.send(`image uploaded successfully : ${image_filename}`);
// const food = new foodModel({
// name: req.body.name,
// description: req.body.description,
// price: req.body.price,
// category: req.body.category,
// image: image_filename,
// });
// try {
// await food.save();
// res.json({ success: true, message: 'Thêm món ăn thành công' });
// } catch (error) {
// res
// .status(500)
// .json({ success: false, message: 'Lỗi khi thêm món ăn', error });
// }
};
foodRouter.post('/add', upload.single('image'), addFood);
module.exports = foodRouter;
试运行结果
控制台日志生成为:
L@3000
图片上传成功:1734017292412 +“-”+blob
为您提供指导
请仔细阅读 server.js 中的示例代码。记下 FormData 对象的创建和填充其中的字段。请确保将图像内容分配给名为“image”的字段,这是强制性的,否则后端将失败,因为相同的名称已被硬编码在中间件中。