Проблема при попытке добавить мои отдельные продукты в корзину
Я создал кнопку на своей веб-странице, я хочу добавить мой отдельный продукт в корзину при нажатии на эту кнопку, но по какой-то причине я получаю следующую ошибку:
productindividual?id=1:117
POST http://127.0.0.1:8000/apiadd/ 500 (Внутренняя ошибка сервера)
addToCart.onclick @ productindividual?id=1:117
VM4764:1 Uncaught (in promise) SyntaxError: Неожиданная лексема I в JSON в позиции 0
Promise.then (async)
addToCart.onclick @ productindividual?id=1:129
Ниже приведен мой код:
<script>
window.onload = ()=>{
let params = window.location.search;
let urlParams = new URLSearchParams(params);
let productID = urlParams.get("id");
// http://127.0.0.1:8000/api/products/id
if(productID != null && typeof(productID)!= 'undefined'){
fetch('http://127.0.0.1:8000/api/products/'+productID)
.then(resp => resp.json())
.then(data => {
console.log(data);
if('detail' in data){
// display some generic product not found error
alert("Product Not Found!");
}
else{
let name = data['name'];
let desc = data['description'];
let price = data['price'];
let image= data['image'];
// display the product data
let specific1Tag = document.getElementById("myname"); // returns the specific DOM node , the P tag with id="myparagraphid"
specific1Tag.innerHTML=name;
let specific2Tag = document.getElementById("mydesc"); // returns the specific DOM node , the P tag with id="myparagraphid"
specific2Tag.innerHTML=desc;
let specific3Tag = document.getElementById("myprice"); // returns the specific DOM node , the P tag with id="myparagraphid"
specific3Tag.innerHTML=price;
let specific4Tag = document.getElementById("myimg"); // returns the specific DOM node , the P tag with id="myparagraphid"
specific4Tag.innerHTML=image;
}
});
}
let addToCart = document.createElement("button"); // create a button
document.getElementById("mybutton").appendChild(addToCart)
addToCart.innerHTML = "Add to cart"; // set the text of the button
addToCart.onclick = ()=>{
// code for when the button is clicked
fetch('http://127.0.0.1:8000/apiadd/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '+localStorage.getItem("access")
},
body: JSON.stringify({
"product_id": parseInt(productID)
})
})
.then(response=>response.json())
.then(data=>{
// display an add to cart success message
console.log(data)
});
}
}