上传图片时出现错误500(内部服务器错误)

时间:2019-07-10 15:09:01

标签: node.js heroku cloudinary

当我尝试使用cloudinary上传图片时,出现错误500。 它既不能在本地运行,也不能在将服务器部署到Heroku上时使用。

我已经在Heroku和环境中设置了config var。文件:https://i.stack.imgur.com/ZJxeq.png

在控制台中,出现此错误:

  

POST https://world-map-mq.herokuapp.com/country/create 500(内部服务器错误)。

     

错误:请求失败,状态码为500

     

在createError(createError.js:17)处。

     

定居(settle.js:19)。

     

在XMLHttpRequest.handleLoad(xhr.js:60)处。

在Heroku中,我的日志如下:

  

2019-07-12T14:16:14.091247 + 00:00 app [web.1]:服务器已启动

     

2019-07-12T14:16:15.212574 + 00:00 heroku [router]:at = info method = OPTIONS path =“ / country / create” host = world-map-mq.herokuapp.com request_id = d6c8ca5b- 18a4-48e2-9846-36911d07c5cd fwd =“ 92.151.32.102” dyno = web.1 connect = 1ms service = 14ms status = 204 bytes = 494 protocol = https

     

2019-07-12T14:16:15.821978 + 00:00 heroku [router]:at = info method = POST path =“ / country / create” host = world-map-mq.herokuapp.com request_id = 1eab82fd- df0c-4ad4-950f-17592cd6257e fwd =“ 92.151.32.102” dyno = web.1 connect = 0ms service = 500ms status = 500 bytes = 499 protocol = https

上传是回调:

const cloudinary = require("cloudinary").v2;
require("dotenv").config();
const uid2 = require("uid2");

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET
});

const uploadPictures = (req, res, next) => {
  const files = req.body.files;
  let filesUploaded = 0;

  if (files && files.length) {
    files.forEach(file => {
      // Je crée un nom spécifique pour le fichier
      const name = String(uid2(16));
      cloudinary.uploader.upload(
        file,
        {
          public_id: `/country/${req.body._id}/${name}`
        },
        (error, result) => {
          if (error) {
            return res.status(500).json("Une erreur est survenue");
          }
          pictures.push(result);
          filesUploaded++;
          if (filesUploaded === files.length) {
            req.pictures = pictures.map(pic => pic.secure_url);

            console.log(req.pictures);
            // ... et je poursuis ma route avec `next()`
            next();
          }
        }
      );
    });
  } else {

    next();
  }
};

module.exports = uploadPictures;

这是我使用回电的路线部分:


router.post("/country/create", uploadPictures, async (req, res, next) => {
  try {
    const countryKnown = await Country.findOne({
      countryVisited: req.body.countryVisited
    });
    // const countryVisitedCode = ;
    if (countryKnown) {
      res.json({ message: "Country already existing" });
    } else {
      const newCountry = new Country({
        countryVisited: req.body.countryVisited,
        countryVisitedCode: countries.getCode(req.body.countryVisited),
        description: req.body.description,
        title: req.body.title,
        pictures: req.pictures
      });
      await newCountry.save(function(err) {
        return res.status(200).json({
          _id: newCountry._id,
          countryVisited: newCountry.countryVisited,
          countryVisitedCode: newCountry.countryVisitedCode,
          description: newCountry.description,
          title: newCountry.title,
          pictures: newCountry.pictures,
          message: "Created"
        });
      });
    }
  } catch (error) {
    console.log("yolo", { error });
    res.status(400).json({ error: error.message });
  }
});

// 2*1 READ
router.get("/country", async (req, res) => {
  try {
    const country = await Country.find();
    res.json(country);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

这是React中最重要的部分:


handleSubmit = async event => {
    event.preventDefault();
    try {
      const response = await axios.post(
        "https://world-map-mq.herokuapp.com/country/create",
        {
          countryVisited: this.state.countryVisited,
          description: this.state.description,
          title: this.state.title,
          files: this.state.files
        }
      );
      this.setState({
        countryVisited: "",
        description: "",
        title: "",
        files: []
      });
    } catch (error) {
      console.log(error);
      this.setState({ error: error });
      alert({ error: error.message });
    }
  };


 handleFiles = files => {
    const newFiles = [...this.state.files, ...files.base64];
    this.setState({ files: newFiles });
  };

render() {
    if (this.state.isLoading) {
      console.log("loading");
      // ce que l'on veut render avant le chargement
      return null;
    }
    // ce que l'on veut render avant le chargement
    return (
      <div>
        <form onSubmit={this.handleSubmit}>

 <ReactFileReader
            fileTypes={[".png", ".jpg"]}
            base64={true}
            multipleFiles={true}
            handleFiles={this.handleFiles}
          >
            <div>Choisir une photo</div>
          </ReactFileReader>
   <input type="submit" value="Valider" />
        </form>
      </div>

 );
  }
}

您能帮我解决这个问题的正确方向吗? 在此先感谢:)

0 个答案:

没有答案