在表单中,我可以进行两次api调用吗



所以我正在制作一个表单,将对象的名称和图像路径保存在数据库中。此外,我需要将图像保存在我的目录中,以便以后可以检索它们。在这种情况下,我可以在哪里添加对";http://localhost:5000/products"?

return (
<>
<form
className="modal-container"
action="http://localhost:5000/upload"
method="post"
enctype="multipart/form-data"
>
<div className="modal-box">
<input
type="text"
placeholder="Name of the product"
className="btn-input-text"
name="product-name"
onChange={(e) => setName(e.target.value)}
></input>
<input
type="file"
accept="image/*"
className="btn-input-image"
name="product-image"
onChange={(e) => setImage(e.target.value)}
></input>
<input type="submit" value="submit" />
<span className="btn-close" onClick={onClose}></span>
</div>
</form>
</>
);

添加产品:

app.post("/products", async (req, res) => {
try {
const { name, description, image } = req.body;
const newProduct = await pool.query(
"INSERT INTO products (product_name, product_description, product_image) VALUES ($1, $2, $3) RETURNING *",
[name, description, image]
);
res.json(newProduct.rows[0]);
} catch (err) {
console.error(err.message);
}
});

将图像保存在我的目录中(使用multer(:

app.post("/upload", upload.single("product-image"), async (req, res) => {
console.log(req.file);
res.send("Image Uploaded");
});

谢谢!

您可以用一个api调用同时完成这两项工作。您的图像通过上传中间件保存在目录中。

您可以通过req.file访问post route内部文件的详细信息,通过req.body访问其他字段的内容。

您可以将投递路线合并为一个上传路线。您还可以将文件详细信息保存在数据库中,以便以后检索文件。例如rq.file.originalname

app.post("/upload", upload.single("product-image"), async (req, res) => {
const { name, description} = req.body;
const image = req.file.originalname;
const newProduct = await pool.query(
"INSERT INTO products (product_name, product_description, product_image) VALUES ($1, $2, $3) RETURNING *",
[name, description, image]
);

console.log(req.file);
res.send("Image Uploaded");
});

使用React,您可以绕过表单通过POST请求向一个API端点提交数据的默认行为,并编写自己的使用两个API的handleSubmit函数。

最新更新