首页 > 解决方案 > 投掷者;// 未处理的 'error' 事件 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头

问题描述

我尝试上传产品(包括图片),我在此视频上使用了相同的代码https://www.youtube.com/watch?v=GCmjLIEtJbA&t=206s,但它未能上传产品?,但服务器给了我200 res,然后快递应用程序崩溃了,你能帮我解决这个问题吗?

这是我的 UploadPage 组件(React):

const onSubmit = (event) => {
    event.preventDefault();

    // send data to server
    const variables = {
      writer: props.user.userData._id,
      title: TitleValue,
      description: DescriptionValue,
      price: PriceValue,
      images: Images,
      continents: ContinentValue,
    };

    Axios.post("/api/product/uploadProduct", variables).then((response) => {
      if (response.data.success) {
        alert("Successfully to upload product");
        props.history.push("/");
      } else {
        alert("Failed to upload product");
      }
    });
  };

这里是产品路线(快递):

router.post("/uploadProduct", auth, (req, res) => {
  // save all data from the client to database

  const product = new Product(req.body);

  product.save((err) => {
    // if fail
    if (err) {
      return res.status(400).json({ success: false, err });
    }

    // if success
    return res.json(200).json({ success: true });
  });
});

这也是我的 FileUpload 组件(React):

const onDrop = (files) => {
    let formData = new FormData();
    const config = {
      header: {
        "content-type": "multipart/form-data",
      },
    };

    formData.append("file", files[0]);

    // save the image inside the node server
    Axios.post("/api/product/uploadImage", formData, config).then(
      (response) => {
        if (response.data.success) {
          setImages([...Images, response.data.image]);

          props.refreshFunction([...Images, response.data.image]);
        } else {
          alert("Failed to save the Image in server");
        }
      }
    );
  };

前端搞砸了后端吗?

谢谢,对不起我的英语不好。

标签: javascriptreactjsexpress

解决方案


由我自己解决,在我的(Express)代码中的某处有这样的代码:

const storage = multer.diskStorage({
  // where i want to save the file
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  // more code
});

然后我将其更改为:

const storage = multer.diskStorage({
  // where i want to save the file
  destination: (req, file, cb) => {
    cb(null, "./uploads/");
  },
  // more code
});

推荐阅读