I have made an endpoint, that returns all products in JSON format. I am trying to display the data from each product, on my index.html page. But I dont seem to able to get to data correct using Axios, this is my first time using axios, so please bare with me.
The endpoint/route /api/products/getAllProducts returns the following JSON
{
"message": "Fetched products..",
"data": [
{
"Product_ID": "017c24f4-8bd6-4bfc-a93e-f6f5d2426f6f",
"Product_title": "PC",
"Product_desc": "PC",
"Product_price": 1000,
"Product_picture": null,
"Product_color": "Blue",
"Product_location": 2150,
"Product_category": "Clothes",
"Product_created": "2022-04-13T00:00:00.000Z"
},
{
"Product_ID": "1",
"Product_title": "fisk",
"Product_desc": "fisk med skind",
"Product_price": 100,
"Product_picture": null,
"Product_color": "grøn",
"Product_location": 2100,
"Product_category": "mad",
"Product_created": "2022-04-13T00:00:00.000Z"
}
]
}
My code so far returns following error
TypeError: products.map is not a function at showProducts (index.js:9:34)
This is my code - I understand that since I am not getting the data correct, I cant use .map property, but I cannot figure out, what I am missing to get the data correctly.
const productsDOM = document.querySelector(".productsDOM");
const showProducts = async () => {
try {
const { data: products } = await axios.get(
"http://localhost:3000/api/products/getAllProducts"
);
const allProducts = products.map((product) => {
return `<h1>${Product_title}</h1>`
})
productsDOM.innerHTML = allProducts
} catch (error) {
console.log(error);
}
};
showProducts();
Thank you in advance!
CodePudding user response:
Axios response the data (your object) in the data (axios response object) field. So the axios response look like:
data: {
"message": "Fetched products..",
"data":[... your products...]
}
}
and cause you just destructuring the axios response object. You have to destructuring again.