使用Knex向MySQL插入数据失败:Cannot read properties of undefined报错排查
Knex向MySQL插入数据失败问题解决
错误根源
你的/signUp路由处理函数参数写错了——把Express路由的第三个参数(本该是next)写成了db,这直接覆盖了全局定义的Knex实例,导致函数内部的db变成undefined,调用db('users').insert()时就会抛出Cannot read properties of undefined (reading 'insert')错误。
修复后的完整代码
只需删除路由参数里多余的db,直接使用全局的Knex实例即可:
const db= knex ({ client: 'mysql2', connection: { host: '127.0.0.1', port: 3306, user: 'root', password: '', database: 'transaction_app' } }); app.get('/', (req, res) => { res.send('App is running') }); // 移除参数中的db app.post('/signUp', (req, res) => { const {name, email, mobile, password}=req.body; const hash=bcrypt.hashSync(password, 10); db('users') .insert({ name: name, email: email, mobile: mobile, password: hash }) .then(data=>{ res.send(data); }) .catch(err=>{ res.send(err); }) }); app.get('/fetch',(req,res)=>{ db.select('*').from('users') .then(data=>{ res.send(data); }) .catch(err=>{ res.send(err); }) }) app.listen(3000, () =>{ console.log('Server started on port 3000'); });
额外优化建议
- 确保已添加
express.json()中间件,否则Postman发送的JSON参数无法被解析,req.body会是undefined:
app.use(express.json());
- 错误处理可以更规范,返回JSON格式的错误信息:
.catch(err=>{ res.status(500).json({error: err.message}); })
原控制台报错信息
Server started on port 3000 users TypeError: Cannot read properties of undefined (reading 'insert') at D:\Documents\Atoa Assignment\server.js:35:3 at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5) at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5) at D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:284:15 at Function.process_params (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:346:12) at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:280:10) at cors (D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:188:7) at D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:224:17
Postman请求截图

内容的提问来源于stack exchange,提问作者NevinTroy
相关产品推荐
相关产品推荐

