我一直在尝试创建一个简单的web应用程序,在那里你可以发布图像和一些描述。它是为一个Instagram克隆项目准备的。我在后端使用multer和express来解析正文和文件,它工作得很好。问题出在前端。我提供了一个表单,您可以在其中放置名称、描述和要上传的图像,然后使用Fetch API将正文发送到后端的api。
我注意到,尽管对form sumbit事件使用了event.preventDefault()和event.stopPropagation(),但每次提交表单时页面都会重新加载。
此外,我已经意识到它只有在上传文件时才会这样做,事实上,如果我离开名称和描述,它不会重新加载页面,而如果我在那里上传文件,它只会重新加载它。
这是fetch API的错误,还是我没有考虑到什么?
以下是处理对我的api的fetch请求的前端代码:
const instaForm = document.getElementById("post-pic");
instaForm.addEventListener("submit", (event) => {
event.preventDefault();
event.stopPropagation();
let instaFormData = new FormData(instaForm);
let url = `${baseUrl}/create-insta`;
fetch(url, {
method: "POST",
body: instaFormData,
})
.then((data) => data.json())
.then((response) => {
instaForm.reset();
console.log(response);
})
.catch((err) => console.error(err));
});考虑一下,如果我将文件的输入留空,页面不会重新加载,因此这肯定是文件上传的问题。
目前,对于调试,我的API只发送回一个简单的“已接收”响应,而不发送任何其他响应。
HTML表单
<form method="POST" id="post-pic" enctype="multipart/form-data">
<input
type="text"
id="name"
name="name"
placeholder="Enter a name..."
/>
<textarea
name="description"
id="description"
rows="10"
placeholder="A short description..."
></textarea>
<input type="file" id="picture" name="insta" />
<button id="publish" type="submit">Publish</button>
</form>发布于 2021-07-14 23:14:14
您应该在单击表单按钮时捕获事件。
试试这个:
<form method="POST" id="post-pic" enctype="multipart/form-data">
<input
type="text"
id="name"
name="name"
placeholder="Enter a name..."
/>
<textarea
name="description"
id="description"
rows="10"
placeholder="A short description..."
></textarea>
<input type="file" id="picture" name="insta" />
<button id="publish" type="button">Publish</button>
</form>JS脚本:
const instaForm = document.getElementById("post-pic");
const buttonForm = document.getElementById("publish");
buttonForm.addEventListener("click",(event) => {
event.preventDefault();
let instaFormData = new FormData(instaForm);
let url = `${baseUrl}/create-insta`;
fetch(url, {
method: "POST",
body: instaFormData,
})
.then((data) => data.json())
.then((response) => {
instaForm.reset();
console.log(response);
})
.catch((err) => console.error(err));
});
}我希望它能帮助你。致以问候。
https://stackoverflow.com/questions/68380035
复制相似问题