Node.js导出Map对象后导入出现TypeError/undefined问题
问题:导入Map对象时出现undefined报错
相关文件代码
launches.model.js
const launches = new Map(); const launch = { flightNumber: 100, mission: "Kepler Exploration X", rocket: "Explorer IS1", launchDate: new Date("December 27,2030"), destination: "Kepler-442 b", customer: ["ZTM", "NASA"], upcoming: true, success: true, }; launches.set(launch.flightNumber, launch); console.log(launches); module.export = { launches, };
该文件执行时console.log输出:
[Map Iterator] { { flightNumber: 100, mission: 'Kepler Exploration X', rocket: 'Explorer IS1', launchDate: 2030-12-26T18:30:00.000Z, destination: 'Kepler-442 b', customer: [ 'ZTM', 'NASA' ], upcoming: true, success: true } }
launches.controller.js
const { launches } = require("../../models/launches.model"); console.log(launches.values());
该文件执行时console.log报错:
c:\Users\kulji\Box\PROJECTS\NODE\NASA-PROJECT\server\src\routes\launches\launches.controller.js:3 console.log(launches.values()); ^ TypeError: Cannot read properties of undefined (reading 'values')
问题原因及修复
问题出在launches.model.js的导出语句上——你写了module.export,但Node.js中正确的导出语法是module.exports(注意末尾的s)。
修改launches.model.js的最后一段代码:
// 原错误代码 module.export = { launches, }; // 修改后正确代码 module.exports = { launches, };
修改后,launches.controller.js就能正确导入launches Map对象,调用values()方法也不会再报错。
内容的提问来源于stack exchange,提问作者kuljit-dhanoa
相关产品推荐
相关产品推荐

