如何正确获取并处理module.exports导出函数的返回值
修复方案
核心问题
你遇到的返回undefined问题由两处错误导致:
server.js中的封装函数没有写return语句,JS函数无显式return时默认返回undefined- 你没有在
server.js中引入底层的用户创建函数,直接调用userCreate会触发递归调用(你导出的函数名就是userCreate,内部调用等于自己调自己),甚至会导致栈溢出
修复步骤
第一步:修改server.js代码
首先引入你写的底层创建用户的函数(假设该函数所在文件名为createUser.js,和server.js同目录,路径请替换为你实际的文件路径),同时给封装函数加上return:
// 引入底层创建用户函数 const baseCreateUser = require('./createUser.js') module.exports.userCreate = function (username, socialname, password) { // 透传底层函数的返回值 return baseCreateUser(username, socialname, password) }
第二步:验证index.js逻辑
修改完成后,你index.js里的原有代码就可以正常打印返回结果:
app.post("/user/create", (req, res) => { const username = req.body.username; const socialname = req.body.socialname; const password = req.body.password; const createdUser = userCommands.userCreate(username, socialname, password); console.log(createdUser) // 可以正常拿到返回对象 // 记得给前端返回响应 res.json(createdUser) });
扩展注意事项
如果后续你的用户创建逻辑加入密码加密、数据库写入等异步操作,需要改用异步写法:
- 底层创建函数改为async函数,异步操作前加await
- server.js的封装函数也改为async函数
- index.js的路由回调加async,调用userCreate前加await
示例异步版代码:
// 异步版createUser.js const bcrypt = require('bcrypt') const { nanoid } = require('nanoid') module.exports = async function(username, socialname, password) { // 异步密码加密 const hash = await bcrypt.hash(password, 10) const userId = nanoid(8) // 这里可加入异步数据库写入逻辑 return { sucesso: true, message: "User created", userId: userId } }
// 异步版server.js const baseCreateUser = require('./createUser.js') module.exports.userCreate = async function (username, socialname, password) { return await baseCreateUser(username, socialname, password) }
// 异步版index.js路由 app.post("/user/create", async (req, res) => { const username = req.body.username; const socialname = req.body.socialname; const password = req.body.password; const createdUser = await userCommands.userCreate(username, socialname, password); console.log(createdUser) res.json(createdUser) });
内容的提问来源于stack exchange,提问作者Igor Duca
相关产品推荐
相关产品推荐

