I am new to nextjs sever, I am trying to get the file in the backend but getting undefined, On my console, I saw this error Error: SyntaxError: Unexpected end of JSON input I am getting the file on my state successfully but when I try to send it in the backend it shows that error.
My backend
import type { NextApiRequest, NextApiResponse } from "next";
const multer = require("multer");
const path = require("path");
const xlsx = require("node-xlsx");
const fileupload = require("express-fileupload");
var bodyParser = require("body-parser");
const uploadFile = multer().single("image");
type Data = {
name: string;
};
var storage = multer.diskStorage({
destination: function (req: any, file: any, cb: any) {
cb(null, path.resolve(__dirname, "uploads"));
},
filename: function (req: any, file: any, cb: any) {
cb(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
},
});
const uploads = multer({ storage: storage });
export default function handler(req: any, res: NextApiResponse<Data>) {
uploadFile(req, res, function (err: any) {
const file = req.files;
// const filename = file.name;
// const worksheetsArray = xlsx.parse(filename); // parses a file
console.log(file);
res.status(200).json(file);
});
}
here is my uploadFile function in frontend:
const uploadFile = async (e: any) => {
e.preventDefault();
const formData = new FormData();
formData.append("file", file);
formData.append("fileName", fileName);
fetch("/api/hello", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
};