Home > other >  Reactjs Axios Post Requests don't run
Reactjs Axios Post Requests don't run

Time:09-28

I try to make 45 post request to my database, but he always just includes a few rows and throws no errors for the others. I tried some try/catch blocks and also tried axios.all, but when I push my requests array, the requests are getting executed immediately. Sometimes just 5 requests get executed and sometimes 15, but never more.

Here is my client-side code:

    const insertCanteens = () => {

    let requests = [];
    let count = 0;
    canteens.map(canteen => {
        console.log("Post"   canteen.id);
        requests.push(
            Axios.post(`${databaseLocation}/api/insert`, {
            id: canteen.id,
            name: canteen.name,
            city: canteen.city
        }))
        count  ;
    })
    console.log("Count: "   count);
    // axios.all(requests);
    console.log(requests);
};

And here my server-side code:

app.post('/api/insert', (req, res) => {

  const id = req.body.id;
  const name = req.body.name;
  const city = req.body.city;
  const sql = `INSERT INTO canteens (id, name, city) VALUES (?,?,?)`;
  try {
        db.query(sql, [id, name, city], (err, result) => {

              if (err) {
                    console.log(err);
              }
              else {
                    console.log("Sucessfully inserted! aaa");
                    // console.log(result);
              }
        });
  } catch (e) {
        console.log(e);
  }
});

CodePudding user response:

The Axios library return Promises, You are missing the await before the function call like this await Axios.post(...), or alternatively you can use the callback pattern using .then() and .catch().

You can read farther on Promises at the MDN

CodePudding user response:

can you try this one?

const insertCanteens = async () => {
  for await (const canteen of canteens) {
    await Axios.post(`${databaseLocation}/api/insert`, {
      id: canteen.id,
      name: canteen.name,
      city: canteen.city,
    });
  }
};

// please call insertCanteens with await keyword, like this -> await insertCanteens();

await insertCanteens(); // call inside an async scope
  • Related