我在尝试测试获取所有路线时遇到"TypeError: Cannot read property '1' of null"?



我正在构建一个登录系统。当我试图从MySQL数据库获取所有用户来测试系统时,我得到

TypeError: Cannot read property '1' of null
at firstchar (E:vs workmysql signup login systemnode_modulesbody-parserlibtypesjson.js:176:37)
at parse (E:vs workmysql signup login systemnode_modulesbody-parserlibtypesjson.js:79:19)
at E:vs workmysql signup login systemnode_modulesbody-parserlibread.js:121:18
at invokeCallback (E:vs workmysql signup login systemnode_modulesraw-bodyindex.js:224:16)
at done (E:vs workmysql signup login systemnode_modulesraw-bodyindex.js:213:7)
at IncomingMessage.onEnd (E:vs workmysql signup login systemnode_modulesraw-bodyindex.js:273:7)
at IncomingMessage.emit (events.js:388:22)
at endReadableNT (internal/streams/readable.js:1336:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)

怎么了? ?

这是我的代码**

router.get('/', (req, res) => {
db.query('SELECT * FROM users', 
(err, rows, fields) => {
if (err) {
throw err
} 
res.send({rows})

})
});
//* sign up route 
router.post('/sign-up', userValidation.validateRegister, (req, res, next)=>{
db.query(
`SELECT * FROM users WHERE LOWER(user_name) = LOWER(${db.escape(req.body.user_name)})
OR LOWER(email) = LOWER (${db.escape(req.body.email)});`,

(err, result) => {
if(result.length) {
return res.status(409).send({msg:'already in use email/username'})
} else {
// ? username is available => hash the pass
bcrypt.hash(req.body.password, 10, (err, hash)=>{
if(err){
return res.status(500).send({msg: err})
} else {
let email = req.body.email
//? has hashed pw => add to database 
db.query(
`INSERT INTO USERS (id,user_name,email,password,registrated) 
VALUES ('${uuid.v4()}', ${db.escape(req.body.user_name)},'${email}', 
${db.escape(hash)}, now())`,
(err, result) =>{
if (err) {
throw err
return res.status(400).send({msg: err})
}
return res.status(201).send({msg: "Registered!!"})
}


)

}
})
}
}

)
})
router.get('/', (req, res) => {
db.query('SELECT * FROM users', 
(err, rows, fields) => {
if (err) {
throw err
} 
if(!rows) throw 'rows not found !'
res.json({rows});
})
});

每个查询都是一个承诺。需要一段时间才能获得从数据库检索数据的请求结果。在您的代码中,您试图在将它们作为响应返回之前发送rows。所以你需要等待,直到你从db得到数据。

router.get('/', async (req, res) => {
const result = await db.query('SELECT * FROM users', (err, rows, fields) => {
if (err) {
throw err
} 
})
res.send(result)
});

我建议使用asyncawait查询。

相关内容

  • 没有找到相关文章

最新更新