我正在使用 multer 和 cloudinary 构建一个图像上传应用程序。我已经使用 dotenv 正确配置了环境变量。但是,当我尝试使用 Cloudinary 上传文件时,出现错误“必须提供 api_key”。
Cloudinary API 凭据已正确提供和配置,如下面的代码所示:
cloudinary.js
const cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
})
exports.uploads = (file, folder) => {
return new Promise(resolve => {
cloudinary.uploader.upload(file, (result) => {
resolve({
url: result.url,
id: result.public_id
})
}, {
resource_type: "auto",
folder: folder
})
})
}
.env
CLOUDINARY_CLOUD_NAME='my_cloudinary_cloud_name'
CLOUDINARY_API_KEY='my_cloudinary_api_key'
CLOUDINARY_API_SECRET='my_cloudinary_api_secret'
我的 app.js 文件中也正确需要 .env 文件:
app.js
require('dotenv').config({
path: './app/config/.env'
});
如果我在 cloudinary.js 文件中对任何 cloudinary 配置变量进行 console.log,我会得到预期的输出,但是当我尝试在上传路由中使用 cloudinary 时,我会收到必须提供 api_key 的错误。请有人帮我指出我做错了什么?我不想在 cloudinary.js 文件中写出我的 cloudinary 配置变量,因为代码正在发布到 Github。
这是我使用 cloudinary 的发布路线:
const express = require('express'),
Product = require('../app/models/product'),
upload = require('../app/utils/multer'),
cloudinary = require('../app/utils/cloudinary'),
fs = require('fs'),
router = express.Router();
router.post('/products', upload.array('image'), async (req, res) => {
const uploader = async (path) => await cloudinary.uploads(path, 'Images');
const urls = []
const files = req.files
for (const file of files) {
const {
path
} = file;
const newPath = await uploader(path)
urls.push(newPath)
fs.unlinkSync(path)
}
const name = req.body.name
const product = new Product({
name: name,
imageone: urls[0].url,
imagetwo: urls[1].url,
imagethree: urls[2].url,
imagefour: urls[3].url
})
product.save(function (err, prod) {
if (err) {
throw err
} else {
req.flash('success', "You have added a new product.")
res.redirect("/dashboard")
}
})
})
module.exports = router;
使用 Node.js v2,可以如以下代码示例所示进行声明,如安装设置文档中所述(即 require('cloudinary').v2):
var cloudinary = require('cloudinary').v2;
cloudinary.config({
cloud_name: '<YOUR_CLOUD_NAME>',
api_key: '<YOUR_API_KEY>',
api_secret: '<YOUR_API_SECRET>',
secure: true
});
cloudinary.uploader.upload("my_image.jpg",
function(error, result) {
console.log(result, error);
});
它是如此简单,你只需要从环境中删除额外的 ' ' 和 " "
CLOUDINARY_CLOUD_NAME='my_cloudinary_cloud_name'
CLOUDINARY_API_KEY='my_cloudinary_api_key' CLOUDINARY_API_SECRET='my_cloudinary_api_secret'