简体   繁体   English

构建后无法将照片从 React 前端发送到表达后端(create-react-app)

[英]Cant send photo from React frontend to express backend after build (create-react-app)

Ok so i have an MERN app (CRA) and photo upload.好的,所以我有一个 MERN 应用程序 (CRA) 和照片上传。 Everything works great but when i will do npm run build i cant send photo (over 1MB) to backend.一切正常,但是当我执行 npm 运行构建时,我无法将照片(超过 1MB)发送到后端。 I've used postman to test and again worked great:).我已经使用 postman 进行测试并再次工作得很好:)。 In development mode its working.在开发模式下它的工作。 Something is blocking requests from frontend when i want to upload photos.当我想上传照片时,有些东西阻止了来自前端的请求。 I've checked logs with morgan and it shows that this request with large photo upload didnt happen.我已经检查了 morgan 的日志,它表明这个带有大照片上传的请求没有发生。 Im using axios to communicate with backend and express file upload but backend works well.我使用 axios 与后端通信并快速上传文件,但后端运行良好。 I dont know what is blocking my photos.我不知道是什么挡住了我的照片。 Also express file upload in debuging mode is telling that "Request is not eligible for upload!"调试模式下的快速文件上传也告诉“请求不符合上传条件!”

action in redux: redux 中的操作:

  export const addGalleryPhoto = (file) => async (dispatch) => {
  const config = {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  };
  try {
    await axios.put(`/api/v1/config/uploadGalleryPhoto`, file, config);
    dispatch(getPhotos());
  } catch (err) {
    const errors = err.response.data.error.split(",");
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error, "error")));
    }
    dispatch({ LOAD_PHOTOS_FAILED });
  }
};

controller in node: controller 在节点:

exports.uploadGalleryPhoto = asyncHandler(async (req, res, next) => {
  if (!req.files) {
    return next(new ErrorResponse(`Dodaj plik`, 400));
  }

  const file = req.files.file;

  // Make sure the image is a photo
  if (!file.mimetype.startsWith("image")) {
    return next(new ErrorResponse(`Możesz wysłać tylko zdjęcia`, 400));
  }

  if (file.size > process.env.MAX_FILE_UPLOAD) {
    return next(
      new ErrorResponse(
        `Zbyt duże zdjęcie. Maksymalny rozmiar pliku: ${Math.round(
          process.env.MAX_FILE_UPLOAD / 1024
        )} MB`,
        400
      )
    );
  }

  file.name = `photo_${uuid()}${path.parse(file.name).ext}`;

  file.mv(`${process.env.FILE_UPLOAD_PATH}/${file.name}`, async (err) => {
    if (err) {
      console.error(err);
      return next(new ErrorResponse(`Problem with file upload`, 500));
    }
    const config = await Config.find();
    await Config.findByIdAndUpdate(config[0].id, {
      galleryPhotos: [...config[0].galleryPhotos, file.name],
    });

    res.status(200).json({
      success: true,
      data: file.name,
    });
  });
});

Gallery component:图库组件:

import React, { useEffect, useState, useRef, Fragment } from "react";
import PropTypes from "prop-types";
import { Card, Modal, Button } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import Spinner from "./../layout/Spinner";
import { connect } from "react-redux";
import {
  addGalleryPhoto,
  getPhotos,
  deletePhoto
} from "./../../store/actions/gallery";

const AdminGallery = ({ photos, addGalleryPhoto, getPhotos, deletePhoto }) => {
  useEffect(() => {
    getPhotos();
  }, [getPhotos]);
  const fileInput = useRef();
  const [value, setValue] = useState("");
  const [formData, setFormData] = useState({
    deleteVisible: false,
    photo: null
  });

  const onSubmit = e => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("file", value);
    addGalleryPhoto(formData);
    setValue("");
  };

  if (photos.loading || photos.photos.null) {
    return <Spinner />;
  } else {
    return (
      <Fragment>
        <div className="admin-gallery">
          <div>
            <input
              type="file"
              style={{ display: "none" }}
              ref={fileInput}
              onChange={e => setValue(e.target.files[0])}
            />
            {value === "" ? (
              <button
                type="button"
                className="btn btn--primary"
                onClick={e => fileInput.current.click()}
              >
                Dodaj plik
              </button>
            ) : (
              <button
                type="button"
                className="btn btn--primary"
                onClick={e => onSubmit(e)}
              >
                Wyślij zdjęcie
              </button>
            )}

            <div>
              {photos.photos.length === 0 ? (
                <div className="no-content">Brak Zdjęć</div>
              ) : (
                <div className="admin-gallery__photo-wrapper">
                  {photos.photos.map(item => {
                    return (
                      <Card
                        style={{ padding: "0 !important" }}
                        key={item}
                        actions={[
                          <DeleteOutlined
                            onClick={() =>
                              setFormData({
                                ...formData,
                                deleteVisible: true,
                                photo: item
                              })
                            }
                          />
                        ]}
                      >
                        <img
                          className="admin-gallery__photo"
                          src={`${process.env.PUBLIC_URL}/uploads/${item}`}
                          alt="photo"
                        />
                      </Card>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </div>
        {formData.deleteVisible && formData.photo !== null ? (
          <Modal
            visible={formData.deleteVisible}
            title="Kasowanie zdjęcia"
            onOk={() => {
              deletePhoto(formData.photo);
              setFormData({ ...formData, deleteVisible: false, photo: null });
            }}
            onCancel={() =>
              setFormData({ ...formData, deleteVisible: false, photo: null })
            }
            footer={[
              <Button
                key="back"
                onClick={() =>
                  setFormData({
                    ...formData,
                    deleteVisible: false,
                    photo: null
                  })
                }
              >
                Zamknij
              </Button>,
              <Button
                key="accept"
                onClick={() => {
                  deletePhoto(formData.photo);
                  setFormData({
                    ...formData,
                    deleteVisible: false,
                    photo: null
                  });
                }}
              >
                Skasuj
              </Button>
            ]}
          >
            <p>Na pewno chcesz skasować to zdjęcie?</p>
          </Modal>
        ) : (
          ""
        )}
      </Fragment>
    );
  }
};

AdminGallery.propTypes = {
  photos: PropTypes.object.isRequired,
  getPhotos: PropTypes.func.isRequired,
  addGalleryPhoto: PropTypes.func.isRequired,
  deletePhoto: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  photos: state.photos
});

export default connect(mapStateToProps, {
  addGalleryPhoto,
  getPhotos,
  deletePhoto
})(AdminGallery);

Ok guys i've found an issue.好的,伙计们,我发现了一个问题。 I have nginx on my droplet and default file size to upload in nginx is set to 1mb.我的Droplet上有nginx,nginx中上传的默认文件大小设置为1mb。 This line in nginx conf will do the job client_max_body_size 100M; nginx conf 中的这一行将完成client_max_body_size 100M; Of course 100M is for example.当然以100M为例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Node(express.js)后端和create-react-app作为前端运行Jest测试 - How to run Jest tests with Node (express.js) backend and create-react-app as frontend 字形和字体不适用于Express服务器和create-react-app构建 - Glyphicons and fonts not working with Express server and create-react-app build 在 express 服务器上提供 create-react-app 构建文件 - Serving create-react-app build files on express server 在单个 Azure 应用程序中使用 Express 后端反应应用程序(通过 create-react-app)? - React app (via create-react-app) with Express backend in single Azure app? 使用 create-react-app 时在后端和前端之间共享模型 - Share model between backend and frontend when using create-react-app 在 create-react-app 上构建后使用静态 JSON 文件 - Use static JSON file after build on create-react-app 在 create-react-app 上运行构建后的空白页面 - Blank page after running build on create-react-app 使用 create-react-app 构建后如何修复白屏? - How to fix the white screen after build with create-react-app? 在弹出以构建组件库之后配置create-react-app - Configuration for create-react-app after ejecting to build a component library 在生产环境中使用带有Express的Create-React-App - Using Create-React-App with Express in production
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM