I am building a login system. When I try to get all users from MySQL DB to test the system and I get
TypeError: Cannot read property '1' of null
at firstchar (E:\vs work\mysql signup login system\node_modules\body-parser\lib\types\json.js:176:37)
at parse (E:\vs work\mysql signup login system\node_modules\body-parser\lib\types\json.js:79:19)
at E:\vs work\mysql signup login system\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (E:\vs work\mysql signup login system\node_modules\raw-body\index.js:224:16)
at done (E:\vs work\mysql signup login system\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (E:\vs work\mysql signup login system\node_modules\raw-body\index.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)
what's wrong????
that's my code**
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});
})
});
Each query is a promise. It takes some time until you get the result of your request to retrieve data from the database. In your code, you are trying to send rows
before you get them back as a response. So you need to wait until you get data back from db.
router.get('/', async (req, res) => {
const result = await db.query('SELECT * FROM users', (err, rows, fields) => {
if (err) {
throw err
}
})
res.send(result)
});
I recommend using async
and await
when querying.