Hello,
I have a lesson with javascript for beginner, and i have an issue with the API "post " function. I don’t understand why my code doesn’t run. The aim is to post a new work (new image with title and catégory) or is to publish changement. There is my javascript code. If you see an error, please tell me. Thank a lot. here is my repo github :
And here is my code :
/* Send the image to server */
let image;
const submitButton = document.querySelector("#submit-button");
const titleInput = document.querySelector("#title");
const categorySelect = document.querySelector("#category");
const background = document.querySelector(".background");
const img = document.createElement("img");
submitButton.addEventListener("click", function(event) {
event.preventDefault();
const title = titleInput.value;
const category = categorySelect.value;
console.log(image);
if (!title || !category) {
console.error("les champs sont tous requis");
return;
}
if (!image) {
console.error("Une image est obligatoire");
}
const formData = new FormData();
formData.append("image", image, image.name);
formData.append("title", title);
formData.append("category", category);
try {
const response = fetch("http://localhost:5678/api/works", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${sessionStorage.token}`
},
body: formData
});
submitButton.style.backgroundColor = "#1D6154";
}
catch (error) {
console.error(error);
submitButton.style.backgroundColor = "#A7A7A7";
}
});
/* upload an image */
let imgSrc;
document.querySelector(".add-photo").addEventListener("click", function() {
const input = document.createElement("input");
input.type = "file";
input.accept = "image/jpg, image/png";
input.click();
/* Check the file type and size */
input.addEventListener("change", async function() {
image = input.files[0];
if (image.type !== "image/jpg" && image.type !== "image/png") {
document.getElementById("errorMessage").innerHTML = "jpg ou png obligatoire";
return;
}
if (image.size > 4 * 1024 *1024) {
document.getElementById("errorMessage").innerHTML = "4mo maximum";
return;
}
/* Replace by image loaded, the default message jpg png 4mo max */
background.innerHTML = "";
const reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = function() {
img.src = reader.result;
imgSrc = reader.result;
img.style.width = "30%";
background.appendChild(img);
if (titleInput.value && categorySelect.value && img.src) {
submitButton.disabled = false;
}
else {
submitButton.disabled = true;
}
}
});
});
/* take categories from API in loading new image*/
async function getCategories() {
const response = await fetch("http://localhost:5678/api/categories");
const categories = await response.json();
const select = document.querySelector("#category");
for (let i = 0; i < categories.length; i++) {
let option = document.createElement("option");
option.value = categories[i].id;
option.innerHTML = categories[i].name;
select.appendChild(option);
}
}
getCategories();
/* function submit button valider */
function validate() {
if (titleInput.value && categorySelect.value && img.src) {
submitButton.disabled = false;
}
else {
submitButton.disabled = true;
}
}
titleInput.addEventListener("input", validate);
categorySelect.addEventListener("input", validate);
validate();
/* publish all work on index.html */
const publish = document.querySelector(".publish");
publish.addEventListener("click", function() {
console.log("publish");
const portfolio = document.getElementById("portfolio");
portfolio.innerHTML = "";
fetch("http://localhost:5678/api/works", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${sessionStorage.token}`
},
body: JSON.stringify({
title: titleInput.value,
category: categorySelect.value,
image: imgSrc
})
})
.then(function (response) {
return response.json();
})
.then(function (work) {
displayPortfolio(work);
})
.catch(function (error) {
console.error(error);
});
});