在 React JS + Express JS 中使用 formdata 发送数据时,后端获取的数据为“未定义”

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

我有一个项目,前端使用 React,后端使用 Express。我想创建一个编辑数据的功能。发送的数据包括一个文件,因此我使用 React 中的 formData() 。在发送之前,我检查了 formData 的内容并且它们存在。但发送到后端后,结果是不确定的。为什么会出现这种情况?

这是我的代码 在前端,

modal.jsx

const EditModal = ({type, isOpen, setIsOpen, rowId, onEditSuccess }) => {
  const [shipAgentName, setShipAgentName] = useState("");
  const [shipAgentCompany, setShipAgentCompany] = useState("");
  const [arrivalSchedule, setArrivalSchedule] = useState("");
  const [arrivalDestination, setArrivalDestination] = useState("");
  const [departureSchedule, setDepartureSchedule] = useState("");
  const [departureDestination, setDepartureDestination] = useState("");
  const [file, setFile] = useState(null);
  const [filename, setFilename] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          "http://localhost:3001/api/ship/arrival/" + rowId,
          {
            method: "GET",
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        if (response.ok) {
          const data = await response.json();
          setShipAgentName(data.shipAgentName);
          setShipAgentCompany(data.shipAgentCompany);
          if(type === "arv"){
            setArrivalSchedule(data.arrivalSchedule);
            setArrivalDestination(data.arrivalDestination);
          }else{
            setDepartureSchedule(data.departureSchedule);
            setDepartureDestination(data.departureDestination);
          }
          setFilename(data.document);
        } else {
          console.log("Failed to fetch data");
        }
      } catch (err) {
        console.log(err.message);
      }
    };
    fetchData();
  }, [rowId, token]);

 const editRow = async (e) => {
    e.preventDefault();
    const formDataa = new FormData();
    formDataa.append("document", file);
    formDataa.append("ship_agent_name", shipAgentName);
    formDataa.append("ship_agent_company", shipAgentCompany);
    if(type === "arv"){
      formDataa.append("arrival_schedule", arrivalSchedule);
      formDataa.append("arrival_destination", arrivalDestination);    
    }else{
      formDataa.append("departure_schedule", departureSchedule);
      formDataa.append("departure_destination", departureDestination);
    }
    try {
      const response = await fetch(
        "http://localhost:3001/api/ship/arrival/" + rowId,
        {
          method: "PUT",
          body: formDataa,
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );
      if (response.ok) {
        console.log("Data successfully updated");
        onEditSuccess();
      } else {
        console.log("Failed to update data");
      }
    } catch (err) {
      console.log(err.message);
    } finally {
      setIsOpen(false);
    }
  };

 return (
    <div
      id="popup-modal"
      tabIndex="-1"
      className={
        "overflow-y-auto overflow-x-hidden z-50 justify-center items-center flex fixed bg-[rgba(0,0,0,0.2)] transition transform h-screen w-full"
      }
      onClick={(e) => handleClickOutside(e)}
    >
        // ...
         <form
              className="flex justify-center items-center"
              onSubmit={(e) => {editRow(e, rowId)}}
              encType="multipart/form-data">
              <div className="grid gap-[20px]">
                <div>
                  <div className="pl-[17px] font-bold">Agent Name</div>
                  <div className="pt-[11px]">
                    <input
                      type="text"
                      value={ship_agent_name}
                      onChange={(e) => setShipAgentName(e.target.value)}
                      placeholder="Agents Name"
                      className="pl-[17px] bg-[#83B3CA] placeholder-[#5C5C68] w-[594px] h-[45px] rounded-[10px]" />
        // ...
         </form>
};

在后台。索引.js

const app = express();
const corsOptions = {
    origin: 'http://localhost:3000',
    credentials: true, 
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
};

app.use(cookieParser());
app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/public', express.static(path.join(__dirname, "..", 'public')));
//....
app.put("/api/ship/:type/:id", verifyToken, (req, res) => {
    const id = req.params.id;
    const type = req.params.type;
  
    console.log(req.body.ship_agent_name);

    if(req.body.ship_agent_name === undefined){
        console.log("no data");
        return res.status(500).send({ message: "Error updating data" });
    }
  
    let sqlQuery = "SELECT * FROM departures WHERE id = ?";
    if (type === "arrival") {    
      sqlQuery = "SELECT * FROM arrivals WHERE id = ?";
    }
  
    db.query(sqlQuery, [id], (err, result) => {
      if (err) {
        return res.status(500).send({ message: "Error fetching data" });
      }
      let arrivalSchedule, arrivalDestination, departureSchedule, departureDestination;
      if (result.length > 0) {
        const shipAgentName = req.body.ship_agent_name || result[0].ship_agent_name;
        const shipAgentCompany = req.body.ship_agent_company || result[0].ship_agent_company;
        const document = req.file ? req.file.filename : result[0].document;
  
        if (type === "arrival") {
          arrivalSchedule = req.body.arrival_schedule || result[0].arrival_schedule;
          arrivalDestination = req.body.arrival_destination || result[0].arrival_destination;
        } else {
          departureSchedule = req.body.departure_schedule || result[0].departure_schedule;
          departureDestination = req.body.departure_destination || result[0].departure_destination;
        }
  
        const updateQuery = `
          UPDATE ${type === "arrival" ? "arrivals" : "departures"}
          SET ship_agent_name = ?, ship_agent_company = ?, ${type === "arrival" ? "arrival_schedule" : "departure_schedule"} = ?, ${type === "arrival" ? "arrival_destination" : "departure_destination"} = ?, document = ?
          WHERE id = ?`;
  
        const updateData = [shipAgentName, shipAgentCompany, arrivalSchedule || departureSchedule, arrivalDestination || departureDestination, document, id];
  
        db.query(updateQuery, updateData, (err, result) => {
            if (err) {
                res.status(500).send({ message: "Error updating data" });
            } else {
                res.send({ message: "Data successfully updated" });
            }
        });
      }
    });
});
//...

为什么 console.log(req.body.ship_agent_name) 显示

undefined

reactjs express rest fetch-api multipartform-data
1个回答
0
投票

我真的很抱歉,我只需要在我的端点中添加

upload.single()
中间件。谢谢@WeDoTheBest4You

© www.soinside.com 2019 - 2024. All rights reserved.