admin管理员组文章数量:814823
如何在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
})
}
本文标签: 如何在Expressjs中获取res json值
版权声明:本文标题:如何在Express.js中获取res json值 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1715135445a821431.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论