#828 JSON Parse Error for Image Upload #858
-
Hi, I want to implement an Image Upload via Cloudinary in our App Homemade Remedies (see PR) . The image upload is implemented on a User form for Adding Remedies. The code is all done, but unfortenatly, I get an
, when I upload an image. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Check for Proper File Field in FrontendIn the form data you're sending to the API, ensure that the // api/upload/index.js
// ⬇️ cover instead of image, according to the field nam of your input element.
const file = files.cover[0]; |
Beta Was this translation helpful? Give feedback.
-
Apart from that I found the following issues in your code.
➡️ Extract the async function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const formObject = Object.fromEntries(formData);
const response = await fetch("/api/upload", {
method: "POST",
body: formData,
});
const { url } = await response.json();
const remedyData = {
...formObject,
ingredients: ingredients,
symptoms: selectedSymptoms,
// the wrong key was also set here
imageUrl: url,
};
isEditMode
? onEditRemedy({ remedyData })
: onAddRemedy({ ...remedyData, imageUrl: url });
event.target.reset();
setIngredients([""]);
setSelectedSymptoms([]);
router.back();
}
{
protocol: "http",
hostname: "res.cloudinary.com",
port: "",
pathname: "/**",
} 💡 I want to highlight that these are issues you could have identified yourself by using the console to log key parts of your code. For example, in the image upload process, if you had logged the response from Cloudinary, like this: const response = await fetch("/api/upload", {
method: "POST",
body: formData,
});
console.log(await response.json()); // This would show you what Cloudinary is returning You would have noticed that the |
Beta Was this translation helpful? Give feedback.
Apart from that I found the following issues in your code.
response
from Cloudinary toimage
, which could is an object with multiple pieces of data, but you never actually use the URL for the image that Cloudinary returns. Instead, you are using a placeholder image "/placeholder.jpg" when adding a new remedy.➡️ Extract the
url
from the Cloudinary responseconst { url } = await response.json();
This URL is what we need to display the uploaded image. Then use thisurl
as the value forimageUrl
in theremedyData
. This ensures that the correct image is displayed when you add or edit a remedy.