【问题标题】:cloudinary is returning an empty object when trying to upload an image + the image isn't being uploaded (express server)cloudinary 在尝试上传图像时返回一个空对象 + 图像未上传(快速服务器)
【发布时间】:2021-11-18 08:42:38
【问题描述】:

我正在尝试在快速服务器中使用 cloudinary 实现图像上传,一切正常,但是由于某种原因,cloudinary 上传器的结果是一个空对象,当然图像没有被上传。

上传路线:

const router = require('express').Router() ;

const cloudinary = require('cloudinary');
const auth = require('../middleware/auth');
const authAdmin = require('../middleware/authAdmin');

//cloudinary configs ...
cloudinary.config({
    cloud_name : process.env.CLOUD_NAME, 
    api_key: process.env.CLOUD_API_KEY,
    api_secret: process.env.CLOUD_API_SECRET
});


// upload image...
router.post('/upload',auth , authAdmin, (req, res) =>{
    try {
        if(!req.files || Object.keys(req.files).length === 0)
            return res.status(400).json({msg: 'No files were uploaded.'});
        
        const file = req.files.file;
        if(file.size > 1024*1024) {
            removeTmp(file.tempFilePath);
            return res.status(400).json({msg: "Size too large"});
        }

        if(file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png'){
            removeTmp(file.tempFilePath);
            return res.status(400).json({msg: "File format is incorrect."});
        }

        console.log(req.files) ;
        cloudinary.v2.uploader.upload(file.tempFilePath, {folder: "test"}, async(err, result)=>{
            if(err) throw err;

            removeTmp(file.tempFilePath)

            res.json({public_id: result.public_id, url: result.secure_url})
        })
    } catch (err) {
        return res.status(500).json({msg: err.message});
    }
});



const removeTmp = (path) =>{
    fs.unlink(path, err=>{
        if(err) throw err;
    })
};



module.exports = router ; 

在 .env 文件中:

CLOUD_API_KEY= API_KEY_HERE
CLOUD_NAME: CLOUD_NAME_HERE
CLOUD_API_SECRET= API_SECRET_HERE

当然,我在文件中有我的实际信息,但出于安全原因,我无法在此处发布它们。

当我在邮递员中尝试这条路线时,我得到一个空对象,如下图所示:

我确实尝试了以下方法:

  • 在线查找我的代码是否错误,我找不到我的问题。
  • 检查对我的 api 密钥和秘密和名称的引用是否正确。
  • 检查并尝试了多种方式将这些东西写在.env文件中并查了一下,发现是正确的,没有问题。

【问题讨论】:

  • 当您提高 500 时,您将返回 err.message。您能否尝试返回 err - 输出是什么?

标签: javascript node.js express cloudinary


【解决方案1】:

在@Aleksandar 的评论的帮助下,我能够解决这个问题。

在返回 err 而不是 err.message 后,我收到“您必须提供云名称”的错误。

之后,我可以通过提供正确的云名称轻松修复错误。

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 2017-08-22
    • 2018-02-26
    • 2021-12-02
    • 2020-04-30
    相关资源
    最近更新 更多