这是我的 axios post 请求。
await axios
.post(
status === "register"
? "api/v1/publicUsers/register"
: "api/v1/publicUsers/login",
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
onUploadProgress: (data) => {
setProgress(Math.round((100 * data.loaded) / data.total));
console.log(progress);
},
withCredentials: true,
}
)
这里是后端服务层,用于获取文件上传和其他表单数据。
module.exports.publicUsersService =
(upload.any(),
(req, res) => {
console.log(req.files);
console.log(req.body);
}
)
upload
来自 multerInstance
文件,其中包含:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "../public/uploads/");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
module.exports = upload;
表格片段:
<form onSubmit={handleSubmit} encType="multipart/form-data">
<input
onChange={handleEmail}
type="email"
className="border-black border-2 mt-5 w-72 p-3"
placeholder="Enter your email"
name="email"
id="email"
/>
<br />
<input
onChange={handlePass}
type="password"
className="border-black border-2 mt-5 w-72 p-3"
placeholder="Enter your password"
name="password"
id="password"
/>
<br />
{status === "register" && (
<input
onChange={handleFile}
type="file"
className="border-black border-2 mt-5 w-72 p-3"
required={true}
name="file"
id="file"
/>
)}
<br />
<div className="button flex justify-center bg-blue-600 mt-5 p-3">
{status === "login" ? (
<button className="">Login</button>
) : (
<button className="">Register</button>
)}
</div>
</form>
现在,当我提交表单时,我的
req.file
和 req.body
中没有收到任何数据。
它们是未定义的。
问题出在
publicUsersService
中间件函数上:multer 处理程序永远不会被调用,因为您使用括号/括号表达式定义它,因此它解析为单个/最后一个处理程序(请参阅:括号中的 JavaScript 表达式)。
您需要用方括号/数组定义它,并在其中列出路由处理程序,以便可以调用/链接它们,请参阅:路由处理程序。
改变:
module.exports.publicUsersService =
(
upload.any(),
(req, res) => {
console.log(req.files);
console.log(req.body);
}
)
对此:
module.exports.publicUsersService =
[
upload.any(),
(req, res) => {
console.log(req.files);
console.log(req.body);
}
]
我将我的路线处理程序更新为:
publicUsersRouter
.route("/register")
.post(upload.single("file"), async (req, res) => {
publicUsersService(req,res)
}