如何在Express.js中获取res json值"/>
如何在Express.js中获取res json值
我是node.js的新手。我正在尝试做这样的事情-
我创建了一个添加到购物车的API,首先要检查会话购物车是否存在。如果不存在,我将通过getCartCode(res)
方法创建新的购物车。
app.post('/addToCart', function(req, res) {
console.log('[POST] /addToCart');
var cart = req.body.conversation.memory['cart'];
if(!cart) {
const response = getCartCode(res);
console.log("******* Result ************ : " + response.conversation.memory['cart']); // Giving undefined exception here
}
}
getCartCode-此方法创建购物车并返回我通过res.json返回的代码
function getCartCode(res) {
return createCart()
.then(function(result) {
res.json({
conversation: {
memory: {
'cart': result,
}
}
});
return result;
})
.catch(function(err) {
console.error('productApi::createCart error: ', err);
});
}
现在我想要的是,我想在addToCart API中获得购物车代码作为响应。我正在尝试在console.log中打印购物车代码,但没有打印任何内容并引发异常。
回答如下:这是您必须处理的方式:
app.post('/addToCart', function(req, res) {
const cart = req.body.conversation.memory.cart
if (!cart) {
getCartCode()
.then(function (result) {
res.json({
conversation: {
memory: { "cart": result }
}
})
})
.catch(/* handle errors appropriately */)
return;
}
// return whatever is appropriate here
res.status(...).json(...);
})
function getCartCode() {
return createCart()
.catch(function(err) {
console.error('productApi::createCart error:', err);
throw err
})
}
更多推荐
如何在Express.js中获取res json值
发布评论