Express.js调用Neo4j获取数据返回undefined,API响应为空
问题原因及修复方案
问题根源
- 函数未返回Promise:
getGraphData内部调用了异步的session.run,但整个函数没有返回任何值。then回调里的return cities只是回调函数的返回值,并非getGraphData的返回结果,所以await getGraphData()会得到undefined。 - 错误未向上抛出:原函数的
catch仅打印错误,没有将错误抛出,导致路由层的try/catch无法捕获异常,无法及时返回错误响应。
修复后的代码示例
方案1:让函数返回Promise链
修改module.js:
function getGraphData() { const cityName = 'Milan'; const readQuery = `MATCH (City {name: $cityName})-[:LINKED*1..3]-(city:City) RETURN city`; // 返回session.run的Promise链,让上层可以await return session .run(readQuery, { cityName }) .then(result => { const cities = []; result.records.forEach(record => { cities.push({ title: record._fields[0].properties.name, }); }); return cities; }) .catch(err => { console.log(err); // 抛出错误,让路由层的try/catch捕获 throw err; }); } module.exports.getGraphData = getGraphData;
方案2:用async/await改写(更易读)
修改module.js:
async function getGraphData() { const cityName = 'Milan'; const readQuery = `MATCH (City {name: $cityName})-[:LINKED*1..3]-(city:City) RETURN city`; try { const result = await session.run(readQuery, { cityName }); // 用map替代forEach,代码更简洁 const cities = result.records.map(record => ({ title: record._fields[0].properties.name })); return cities; } catch (err) { console.log(err); throw err; } } module.exports.getGraphData = getGraphData;
路由代码修正
同时补全路由中缺失的代码闭合,调整响应状态码(200更适合完整数据返回):
const { getGraphData } = require('./../db/neo4j'); router.get('/', async (req, res) => { try { const p = await getGraphData(); console.log('p:', p); return res.status(200).json(p); } catch (e) { console.log(e); return res.status(500).json({ error: '获取城市数据失败' }); } });
内容的提问来源于stack exchange,提问作者Александр Сосо
相关产品推荐
相关产品推荐

