我从一个站点返回一个对象,除了其他参数之外还包含一个对象数组。
如果我做console.log(req.body.cart)我打印[{title:'iphone 6',费用:'650'}]
我只需要标题。我尝试了stringify,这不是我想要的,并解析返回500错误。
router.post('/itemstobuy', function(req, res, next){
if(!req.body.name || !req.body.lastname || !req.body.address
|| !req.body.email || !req.body.cart){
return res.status(400).json({message: 'Please fill out all fields'});
}
var mailOptions={
from: 'anEmail@gmail.com',
to: 'anotherEmail@gmail.com',
subject: 'Subject',
html: '<p>Name: ' + req.body.name + '</p>' +
'<p>LastName: ' + req.body.lastname + '</p>' +
'<p>Address: ' + req.body.address + '</p>' +
'<p>Email: ' + req.body.email + '</p>' +
'<p>Cart: ' + JSON.stringify(req.body.cart) + '</p>'
}
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
return res.status(200);
});
我需要按照标题显示项目
'<p>Cart: ' + JSON.stringify(req.body.cart) + '</p>'
上述工作但有很多丑陋的数据,只需要项目的标题。
答案 0 :(得分:0)
试试这个。 '<p>Cart: ' + JSON.parse(req.body.cart).title + '</p>'
答案 1 :(得分:0)
如果购物车中有多件商品,您可以重复这些商品,否则您可以直接访问它req.body.cart[0].title
var cart = req.body.cart;
var html: '<p>Name: ' + req.body.name + '</p>' +
'<p>LastName: ' + req.body.lastname + '</p>' +
'<p>Address: ' + req.body.address + '</p>' +
'<p>Email: ' + req.body.email + '</p>';
html += '<p>Cart:<ul> '+
for(var i=0;i<cart.length;i++) html +='<li> ' + cart[i].title + '</li>';
html +='</ul></p>';
var cart = [ { title: 'iphone 6', cost: '650' }, { title: 'iphone 5', cost: '550' } ];
document.write( '<p>Cart:<ul> ');
for(var i=0;i<cart.length;i++) document.write('<li> ' + cart[i].title + '</li>');
document.write('</ul></p>');
&#13;
答案 2 :(得分:0)
正如评论中所建议的那样:
'<p>Cart: ' +
(req.body.cart || []) //Just to make things not crash and burn if we have no cart
//Take the title from each of the items
.map(function(item){ return item.title; })
//Create a comma-separated string from the titles
.join(', ') +
'</p>'