NodeJS Multer 上传请求确实将图像上传到预期路径,但请求状态处于待处理状态并阻止下一个请求

问题描述 投票:0回答:2

我在函数

fetch
中执行多个
saveProduct
请求,一个请求将文件上传到
/public/images
目录,另一个是将与产品相关的数据上传到
product
表,第一个请求
 POST /api/upload
工作正常,它确实将文件上传到预期目录,但之后该函数停止工作,它不执行请求
POST /api/new-product
,也不执行任何其余代码,
toast
不显示..等,在
network
选项卡中,我注意到请求状态为
pending
,并且它只是永远处于待处理状态,在执行多个
fetch
请求之前,代码工作没有问题。

正面

  const saveProduct = async () => {
    let formData = new FormData();
    formData.append("image", product.image);
    setSubmitted(true);
    if (!product.image || !product.name|| !product.price) {
      return;
    }

    let _products = [...products];
    let _product = { ...product };

      Promise.all([
        await fetch("http://localhost:8000/api/upload", {
          method: "POST",
          body: formData,
        }),
        await fetch("http://localhost:8000/api/new-product", {
          method: "POST",
          body: JSON.stringify(product),
          headers: { "Content-Type": "application/json" },
        }),
      ]).then(() => {
        _products.push(_product);
        toast.current.show({
          severity: "success",
          summary: "Successful",
          detail: "Product Created",
          life: 5000,
        });
        setProducts(_products);
        setProductDialog(false);
        setProduct(emptyProduct);
      });


  };

服务器端

import multer from "multer";
// Initialize router
const routes = Router({ strict: true });

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    return cb(null, "./public/images");
  },
  filename: function (req, file, cb) {
    return cb(null, `${Date.now()}_${file.originalname}`);
  },
});

const upload = multer({ storage });

routes.post("/upload", upload.single("image"), (req, res) => {
  console.log(req.body);
  console.log(req.file);
});

routes.post(
  "/new-team-member",
  [
    // Validation for user name
    body("name")
      .trim()
      .not()
      .isEmpty()
      .withMessage("product name must not be empty")
      .isLength({ min: 10 })
      .withMessage("Full name must be at least 10 characters in length")
      .escape(),

    // Validation for password length
    body("price")
      .trim()
      .not
      .isEmpty()
      .withMessage("price must not be empty"),
  ],
  // tokenValidation(),
  // validate, // Middleware to handle validation errors
  (req, res) => {
    try {
      const { name, price, image } = req.body;

      DB.execute(
        "INSERT INTO `team` (`name`,`price`,`image`) VALUES (?,?,?)",
        [name, price, image]
      );
      res.status(201).json({
        name: name,
        price: price,
        image: image,
      });
    } catch (err) {
      console.log(err);
    }
  }
);
reactjs node.js fetch multer
2个回答
0
投票

发生这种情况是因为您没有在上传 api 中将任何响应从服务器发送回前端,请尝试使用 res.status.().json({}) 发送响应


0
投票

发生这种情况是因为我对每个

await
都使用
fetch
,它应该是
await Promise.all([...])

      await Promise.all([
        fetch("http://localhost:8000/api/upload", {
          method: "POST",
          body: formData,
        }),
        fetch("http://localhost:8000/api/new-team-member", {
          method: "POST",
          body: JSON.stringify(product),
          headers: { "Content-Type": "application/json" },
        }),
      ]).then(() => {
            ...
      });
© www.soinside.com 2019 - 2024. All rights reserved.