Please help solve this problem. I am working with a MERN app. In the app, I upload images to the cloudnary using the API. Then I upload the image on the frontend using secure_url. It works on localhost but does not work on heroku i.e. the image is not uploaded
localhost:
heroku:
Response in browser console:
other images:
upload.js
const express = require("express");
const router = express.Router();
const cloudinary = require("cloudinary");
const { verifyTokenTeacher } = require("./verifyToken");
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", verifyTokenTeacher, (req, res) => {
try {
console.log(req.files);
if (!req.files || Object.keys(req.files).length === 0)
return res.status(400).json({ msg: "Fayl yuklanmangan" });
const file = req.files.file; // oxiridagi file bu query parametr
if (file.size > 1024 * 1024 * 2)
return res.status(400).json({ msg: "Fayl hajmi 2mb dan kam bo'lsin" });
// if file no image
if (
file.mimetype !== "image/jpeg" &&
file.mimetype !== "image/jpg" &&
file.mimetype !== "image/png"
)
return res.status(400).json({ msg: "Faqat JPEG va PNG rasm yuklang!" });
cloudinary.v2.uploader.upload(
file.tempFilePath,
{ folder: "test1" },
async (err, result) => {
if (err) {
throw err;
}
return res
.status(200)
.json({ public_id: result.public_id, url: result.secure_url });
}
);
} catch (err) {
res.status(500).json(err.message);
}
});
using image url in frontend:
<img src={question.image.url} alt="Rasm" />
question model: Question.js
const mongoose = require("mongoose");
const questionSchema = mongoose.Schema(
{
title: {
type: String,
required: true,
},
themeId: {
type: String,
required: true,
},
image: {
type: Object,
default: null,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Question", questionSchema);
create question router: questions.js
router.post("/", verifyTokenTeacher, async (req, res) => {
try {
await Theme.findById(req.body.themeId);
const newQuestion = new Question(req.body);
const savedQuestion = await newQuestion.save();
res.status(201).json(savedQuestion);
} catch (err) {
res.status(500).json({ msg: err.message });
}
});
I was getting the same error while fetching images from cloudinary.
I resolved the error by adding crossorigin="anonymous"
in image tag.
Just add crossorigin="anonymous"
in your img tag like:
<img crossorigin="anonymous" src="https://example.com/image.jpg">
this should resolve the error.