簡體   English   中英

POST 500(內部服務器錯誤)無法在節點服務器上使用 react js 發布表單數據

[英]POST 500 (Internal Server Error) can't post form-data with react js on node server

POST https://waste-alert-api.herokuapp.com/datas 500 (Internal Server Error)

我創建了一個 React 項目,我想在其中上傳帶有一些數據的圖像。 除了 post 方法之外,每個方法都可以正常工作。 為了更好地理解,我添加了 React JS 部分以及 Node Js 代碼。

當我用 POSTMAN 測試時,Node Js 服務器工作正常。

反應 JS

const submitPostHandler = async (data) => {
    try {
      const response = await fetch(
        "https://waste-alert-api.herokuapp.com/datas",
        {
          method: "POST",
          body: data,
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: token,
          },
        }
      );

      console.log(response);
    } catch (err) {
      console.log(err);
    }
  };
    const metaData = {
      "wasteType": enteredWasteType,
      "location": {
        "lat": enteredLat,
        "long": enteredLong,
      },
    };
    console.log(metaData);

    const data = new FormData();
    data.append("image", file);
    data.append("data", metaData);

    props.submitPostHandler(data);

節點 Js

router.post(
  "/datas",
  auth,
  uploadOptions.single("image"),
  async (req, res, next) => {
    const file = req.file;
    if (!file) return res.status(400).send("No image in the request");

    const fileName = file.filename;
    const basePath = `${req.protocol}://${req.get("host")}/uploads/`;
    console.log(req.body.data);
    const newData = JSON.parse(req.body.data);
const data = new Data({
      wasteType: newData.wasteType,
      location: newData.location,
      image: `${basePath}${fileName}`,
      owner: req.user._id,
    });

    try {
      await data.save();
      res.status(201).send(data);
    } catch (e) {
      res.send({ e, error: "something is wrong" });
    }
  }
);


我的 MERN 應用程序也有類似的問題。 我的客戶端 package.json 文件包含帶有 Heroku 創建的應用程序地址的代理密鑰。 但是在本地主機上運行應用程序時,它導致了 500/503 內部服務器錯誤。 首先,我遵循了這個解決方案並將 http-proxy-middleware 安裝到客戶端文件夾中。 其次,在我的 axios.post 方法中,我按照此處的建議將錯誤處理從 err 更改為 err.response.data 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM