我正在尝试使用 multer
或 formidable
上传文件。文件已正确上传并存储在 public
文件夹中。我使用 create-react-app 来启动 React 项目。
当我点击提交按钮上传数据时出现问题。我使用 fetch API 来发出 POST 请求。单击提交按钮后,页面会重新加载,并且我在控制台上登录的所有内容也会刷新。这也得到了回答here ,但我想知道如何防止页面重新加载?我应该将图像存储在 public
文件夹之外吗?
这是我的 handleSubmit()
函数,在提交表单时调用:-
const handleSubmit = async (e) => {
e.preventDefault();
let formData = new FormData();
formData.append("poster", document.getElementById('file').files[0]);
let res = await fetch("http://localhost:5000/api/post/exhibition", {
method: "POST",
body: formData
})
const json = await res.json()
console.log(json)
}
编辑:-处理onSubmit
<form onSubmit={handleSubmit} encType="multipart/form-data">
....
</form>
最佳答案
这是因为当您上传成功后,webpack 会检测到新文件并重新加载页面。
来自https://github.com/facebook/create-react-app/issues/2541#issuecomment-308750412
I don't think we'll do this as it seems like people generally don't use public folder for uploads. And it wouldn't work in production anyway.
I would recommend to use a separate server (which you need anyway) and separate folder for image uploads, and have the app load images from a different host/port (just like it would in production, e.g. from a CDN).
关于javascript - PreventDefault() 方法不阻止页面重新加载 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72847690/