skip to Main Content

I’m doing multiple fetch requests in function saveProduct, one request to upload the file to /public/images directory, the other one is to upload data related to the product to the product table, the first request POST /api/upload works fine and it does indeed upload the file to the intended directory, but then after that the function stops working, it doesn’t do request POST /api/new-product, neither it executes any of the rest of the code, the toast doesn’t show ..etc, in the network tab i noticed that the request status is pending, and it’s just keeps pending forever, the code was working with no problem before doing this multiple fetch requests.

Front side

  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);
      });


  };

server side

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);
    }
  }
);

2

Answers


  1. Chosen as BEST ANSWER

    it happens because im using await for every fetch, it should rather be 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(() => {
                ...
          });
    

  2. It happens because you’re not sending any response back to the frontend from your server in upload api try sending response with res.status.().json({})

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search