我是 NEXT JS 的新手。我正在尝试将一些表单数据从客户端发送到 NEXTJS API。几天来我一直在寻找这个问题的解决方案。关于这个问题有一些解释,但我不太明白。如果有人能告诉我我做错了什么以及为什么表单数据似乎在 NEXTJS 中不起作用,我将不胜感激。
这是我的代码。
================ 客户端。 ===============================
const buttonHandler = (e) =\> {
e.preventDefault();
let formData = new FormData();
formData.append("myImage", imageInput);
formData.append("title", title);
formData.append("description", description);
async function postData() {
try {
const response = await axios(
"http://localhost:3000/api/requests/postdata",
{
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: formData,
}
);
console.log(response, "Successfully sent the data to the backend!");
} catch (e) {
console.log(e, "Getting an error!");
}
}
postData();
};
================ 在 NEXT API 中 ============================
import connectMongoose from "../../../utils/connectMongoose";
import middlewareHandler from "../../../middleware/middlewareHandler";
import Post from "../../../models/posts";
export const config = {
api: {
bodyParser: false,
},
};
export default middlewareHandler.post(async (req, res, next) =\> {
await connectMongoose();
console.log("Connected to the database (upload)!");
try {
const post = new Post({
title: req.body.title,
myImage: req.file.path,
description: req.body.description,
});
const savePost = await post.save();
res.status(200).send(savePost);
} catch (e) {
console.log(e, "Error is occured!");
res.status(500).send(e);
}
});
由于某种原因,Nextjs App 不支持新的 FormData()。即使它在页面目录上运行得很好。
我的解决方法是使用状态来管理字段,然后再进行字符串化。
我相信未来的更新将纠正FormData()的错误。
import React, { useState } from "react";
import axios from "axios";
const ImageUpload = () => {
const [selectedFile, setSelectedFile] = useState(null);
const [formData, setFormData] = useState({
title: "",
description: "",
});
const handleFileChange = (event) => {
setSelectedFile(event.target.files[0]);
};
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value,
}));
};
const handleSubmit = async (event) => {
event.preventDefault();
const json = JSON.stringify(formData);
const headers = {
"Content-Type": "application/json",
};
try {
const response = await axios.post("/api/upload", json, {
headers,
});
console.log("Response:", response.data);
} catch (error) {
console.error("Error:", error);
}
};
return (
<div>
<h2>Image Upload and JSON Data</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="title">Title</label>
<input
type="text"
id="title"
name="title"
value={formData.title}
onChange={handleInputChange}
required
/>
</div>
<div>
<label htmlFor="description">Description</label>
<textarea
id="description"
name="description"
value={formData.description}
onChange={handleInputChange}
required
/>
</div>
<div>
<label htmlFor="image">Image</label>
<input
type="file"
id="image"
name="image"
accept="image/*"
onChange={handleFileChange}
required
/>
</div>
<button type="submit">Upload</button>
</form>
</div>
);
};
export default ImageUpload;