简体   繁体   中英

Error cannot read property of undefined using node.js with mysql

I keep getting this error cannot read property of undefined when the password does not match what is is the database however if it is the same its all fine.

let express = require('express');
let app = express();
let router = express.Router();
let users = require('./users.js');
let ejs = require('ejs');
let pg = require('pg');
let bodyParser = require('body-parser');
let mysql = require('mysql');

let connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
port: 3306,
database: "nodeapp2"
 });
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/input', function(req,res) {
res.sendFile(__dirname + '/views/input.html');
});
app.get('/login', function (req,res) {
   res.sendFile(__dirname + '/views/login.html');
});


app.post('/logincred', function(req, res) {

console.log('req.body');
console.log(req.body);



connection.query("SELECT password FROM logins WHERE password = '"+req.body.password+"'",function(err, result){
    if (err)
        throw err;
        if (result[0].password === req.body.password){
            console.log(req.body.password);
            console.log('password accepted');
            res.redirect('/');
            res.end()
        } else {
            res.redirect('/login')
            res.write('login failed');
            res.end()
        }
});

});

If I input the wrong password and I hit the else clause that when I get the error and I am not sure why.

It looks like the variable res is not declared anywhere in the scope of the anonymous callback function. You're using result in the if condition result[0].password === req.body.password but using res in the if/else clauses. Try using result instead of res ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM