【问题标题】:POST 500 (Internal Server Error) can't post form-data with react js on node serverPOST 500(内部服务器错误)无法在节点服务器上使用 react js 发布表单数据
【发布时间】:2021-10-05 02:01:35
【问题描述】:

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


【问题讨论】:

  • 它是否至少返回错误消息“有问题”?
  • @GrafiCode 不,我得到的回复不是这个Response {type: "cors", url: "https://waste-alert-api.herokuapp.com/datas", redirected: false, status: 500, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 500 statusText: "Internal Server Error" type: "cors" url: "https://waste-alert-api.herokuapp.com/datas"
  • 啊,这是一个 CORS 错误。请看一下这个线程,它是关于 ReactJS 获取和 CORS 错误的:stackoverflow.com/questions/48562406/…
  • 我处理了 CORS 并发布了 json 数据没有问题,但是当我尝试表单数据时,问题就来了......

标签: javascript node.js reactjs server


【解决方案1】:

我的 MERN 应用也遇到了类似的问题。我的客户端 package.json 文件包含 Heroku 创建的应用程序地址的代理密钥。但是在本地主机上运行应用程序时会导致 500/503 内部服务器错误。 首先,我遵循this 解决方案并将http-proxy-middleware 安装到客户端文件夹中。其次,在我的 axios.post 方法中,我按照 here 的建议将错误处理从 err 更改为 err.response.data。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 2017-12-06
相关资源
最近更新 更多