Here is my axios post request.
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,
}
)
Here is the backend service layer for getting the file uploads and other form data.
module.exports.publicUsersService =
(upload.any(),
(req, res) => {
console.log(req.files);
console.log(req.body);
}
)
That upload
is coming from the multerInstance
file which contains:
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 snippet:
<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>
Now when I am submitting my form i am not getting any data in my req.file
and req.body
.
They are undefined.
2
Answers
I updated my route handler to this:
The problem is with the
publicUsersService
middleware function: the multer handler is never called, because you define it with parenthesis/parenthesized expression, so it resolves to the single/last handler (see: Javascript expression in parentheses).You need to define it with square brackets/array, and list route handlers within, so that they can be called/chained, see: Route handlers.
change:
to this: