首页 > 解决方案 > 有人搜索 NULL 对象时的响应

问题描述

我正在尝试从 sql 获取 SAP 对话式 AI 的响应。在下面的代码中,一切正常,但如果有一个空对象,那么代码就会停止。如果有空对象,我需要响应。

app.post('/packers', (req, res) => {
console.log(req.body.nlp.source)
rand = random.number(1, 9)

let hp = req.body.nlp.source

let sql= `SELECT * FROM data where catname = 9 AND address LIKE '%${hp}%' `;
let query = db.query(sql, (err, result)=> {
if (err) throw err;
Shopname = result[rand].shopname;
Adress = result[rand].address;
Mobile = result[rand].mobile;
res.send({
replies: [{ type: 'text',
 content: `Name of shop is ${Shopname} and address is ${Adress} and mobile no is ${Mobile}`,
}],
conversation: {
memory: { key: 'value' }
}
})
})
})

标签: mysqlnode.js

解决方案


您可以使用类似 Lodash get()

// this can throw if nlp isn't defined 
let hp = req.body.nlp.source

// this doesn't throw
let hp = _.get(req, 'body.nlp.source', null)

// For this case it throws if result[rand] isn't defined
Shopname = result[rand].shopname

// you can solve like this
Shopname = result[rand] ? result[rand].shopname : null

推荐阅读