mysql - 有人搜索 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' }
}
})
})
})
解决方案
您可以使用类似 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
推荐阅读
- asp.net-core - 使用 Azure AD 登录进行集成测试
- java - 在服务验证请求的 GET 响应中返回附加参数或用户属性
- rust - 在 x86 macOS 上交叉编译到 i686
- spring - 使用spring cloud gateway HOXTON.SR5停止和启动服务后看不到服务
- office-addins - Office 加载项:自定义选项卡不会在桌面 PP/Excel 中显示,在 365 中可以正常工作
- javascript - 尝试使用 AWS.STS.getSessionToken 和 node.js 无法检索令牌
- python - Scrapy Item Pipelines 和文件命名
- javascript - nginx 1.19.0:上传文件时出现 415 错误
- c# - 如何使用C#将选定列的所有行从一个excel文件复制到另一个文件
- php - JsTree 与 Laravel 的集成