我正在尝试使我的代码准备好将json发送回我的聊天机器人,有人可以告诉我为什么我在此上遇到错误:
const data = '{ "Company Name": companyname, "service type": service }'
try {
const user = JSON.parse(data)
} catch(err) {
console.error(err)
}
这是我的完整下部代码,
//=======================================================================================
// Get the Client data from database
//=======================================================================================
app.get("/Getcompany", function(request, response) {
const cname = request.query.cname, query = `select * from clientdata_nsw where companyname = ${connection.escape(
cname
)}`;
connection.query(query, function(err, rows) {
if (err) {
console.log(err);
return;
}
const data = '{ "Company Name": companyname, "service type": service }'
try {
const user = JSON.parse(data)
} catch(err) {
console.error(err)
}
rows.forEach(function(result) {
console.log(
result.companyname,
result.service,
result.phone,
result.open_times,
result.rating_facebook,
result.rating_goggle
);
});
response.json({})
});
})
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
答案 0 :(得分:1)
第一行本身存在错误
const data = '{ "Company Name": companyname, "service type": service }'
JSON.parse(data)
您必须转义公司名称和服务,因为JSON解析器无法解析公司名称和服务,否则使用JS对象而不是解析字符串并形成JS对象。我不明白为什么在代码中包含这些行,因为它们根本没有用于任何东西。
const data = '{ "Company Name": "companyname", "service type": "service" }'
JSON.parse(data)
使用ES6标准重写整个代码。
const PORT = process.env.PORT;
app.get("/Getcompany", async (request, response) => {
const cname = request.query.cname,
query = `select * from clientdata_nsw where companyname = ${connection.escape(
cname
)}`;
const data = '{ "Company Name": "companyname", "service type": "service" }';
try {
const user = JSON.parse(data);
} catch (err) {
console.error(err);
}
try {
const results = await connection.query(query);
results.forEach(row => {
console.log(
row.companyname,
row.service,
row.phone,
row.open_times,
row.rating_facebook,
row.rating_goggle
);
});
} catch (error) {
console.error(error);
}
response.json({});
});
app.listen(PORT, () => {
console.log(`Your app is listening on port ${PORT}`);
});