首頁  >  問答  >  主體

如何使用axios發送多個請求?

我正在製作一個反應註冊表,其中包含一些欄位(idStudent(主鍵和自動增量),名字,姓氏,...,教師,先決條件),我正在使用Formik &是的用於驗證。

後來,我必須根據先決條件和某些科目獲得的成績將我的應用程式與推薦系統連結(向學生推薦最後一年的專案)。

一開始,我只使用一個表來儲存來自前端表單的數據,

學生(名字,姓氏,...,先決條件)

# 學生可以從包含根據教師的先決條件的反應選擇中選擇先決條件(例如:如果學生學習計算機科學,反應選擇將僅顯示計算機科學先決條件,例如反應,角度,機器學習...)。 考慮到一個學生可以有多個先決條件,因此學生表中的先決條件列將包含所選先決條件的多個 id, 先決條件儲存在我的資料庫中的另一個表格中(先決條件(idFaculty,idPreconditions,先決條件)) 我知道我可以使用 JSON 檔案將多個 id 儲存在一個列中,但是在之前的一些帖子中對 Stackoverflow 進行了一些研究之後,我發現處理 JSON 很困難,特別是如果我想更新一列。 所以我創建了另一個表格來儲存學生在註冊時選擇的先決條件

#(studentPrecessions(idStd(從學生表中引用 idStudent 的外鍵),idPrecession(從先決條件表引用 idPrecessions 的外鍵))

# 我面臨的問題是如何透過 axios 發送兩個貼文的請求,考慮到 考慮到也許我應該使用循環來儲存多行,以防學生選擇多個先決條件。

這就是我所做的:

我的後端檔案

app.post("/registerStudent", (req, res) => {
  const faculty = req.body.faculty;
  const firstName = req.body.firstName;
  const lastName = req.body.lastName;
  const phone = req.body.phone;
  const email = req.body.email;
  const password = req.body.password;
  db.query(
    "INSERT INTO students (email, password, firstName, lastName, faculty, phone) VALUES (?,?,?,?,?,?)",
    [email, password, firstName, lastName, filiere, phone],
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        // store chosen prerequisites
        //result.insertId is the current idStudent of the student who registering
        const idStd = result.insertId;
        const idPrerequisite = req.body.idprerequis;
        db.query(
          "INSERT INTO studentPrerequisites (idStd, idPrerequisite) VALUES (?,?)",
          [idFiliere, idPrerequisite],
          (err, result) => {
            if (err) {
              console.log(err);
            } else {
              res.send("Values Inserted");
            }
          }
        );
      }
    }
  );
});

我的前端程式碼

const onSubmit = (values, actions) => {
    Axios.post("http://localhost:3001/registerStudent", {
      faculty: values.faculty,
      firstName: values.firstName,
      lastName: values.lastName,
      phone: values.phone,
      email: values.email,
      password: values.password,
    })
      .then(() => {
       //preId is an array  that contains the selected prerequisites(id's) from react select  
       //I try to use a for loop to store multiple of prerequisites dynamically in case a 
       //student select multiple prerequisites
        for (let i = 0; i < preId.length; i++) {
            idPrerequisites: preId[i],
        }
      })
      .then(() => {
        console.log("success!");
      });
    actions.resetForm();
  };

P粉316110779P粉316110779206 天前318

全部回覆(1)我來回復

  • P粉976737101

    P粉9767371012024-03-27 18:04:50

    最好透過向您的請求傳遞先決條件陣列來讓後端處理多個先決條件。我也會使用 Knex 和 async/await 來避免大量 .then 連結並利用事務。如果事務中發生任何錯誤,事務將恢復所有查詢。 Knex 也透過內建方法讓查詢資料庫變得超級簡單,而不用編寫原始 SQL。您還應該使用物件解構,而不是執行firstName = req.body.firstName、lastName = req.body.lastName等。您可以在此處了解有關knex以及將資料庫連接到它的更多資訊:https://knexjs.org/guide/#node-js# 另外,為什麼你不對你的密碼進行哈希處理?這是您至少應該做到的最基本的安全性!

    回覆
    0
  • 取消回覆