From Angular I send to node/express an array with the products that the user is going to buy.
From node/express I save the data that comes from the req.body in a buy array like this:
let compra: [] = [];
compra = req.body; // guardo en el array la data del body
console.log(compra);
This is the console output:
[
'Borges Cuenta Buenos Aires',
'1230.00',
1,
'Fuertes, Libres Y Nómadas',
'1290.00',
]
Mercadopago now uses this structure to store the products to be purchased:
// Crea un objeto de preferencia
let preference = {
items: [
{
title: 'Mi producto',
unit_price: 100,
quantity: 1
},
],
};
mercadopago.preferences
.create(preference)
.then(function (response) {
console.log(response.body);
// redirije a pagina de mercadopago
res.redirect(response.body.init_point);
})
.catch(function (error) {
console.log(error);
});
So the idea is to save in this preference object , the products that arrive in the req.body , try doing this:
let compra: [] = [];
let items: [
{
title: "";
unit_price: 0;
quantity: 0;
}
];
compra = req.body;
// paso la data del array compra al array items.
for(let i = 0; i < compra.length; i++){
items[i].title = compra[i];
items[i].unit_price = compra[i];
items[i].quantity = compra[i];
}
// console.log de los datos del array items
for(let item of items){
console.log('item: ' + item);
}
But node shows an error: TypeError: Cannot read property '0' of undefined: .
I think the problem you're having is that you're trying to fill
items[]
with the buy values by trying to access the elements based on the length ofcompra
. The error you get is because you define ititems
as an array of a single element, butcompra
it has more elements and at the momentfor
where the second iteration is done, you end up doing something like:Which is a problem because it exists
compra[2]
, but it doesn't existitems[2]
. I suggest you define an empty array as items and fill it using a method likepush
, something like this:Or better yet, using
for ... of
:UPDATE
Assuming that the data arrives as an array that follows a defined structure in which every 3 elements represent a purchase, then I propose something like:
I suggest that each element should be individually encapsulated, this structure that is being used is not adequate and does not take advantage of the language that you are using. It is more complicated to read, requires more code, is more prone to errors, requires additional verification, and is not easily scalable.
A suitable format for
compra
would be something like:Following the advice, a solution to load the products of the req.body in the preference object was:
In the checkout function of the controller.ts