【问题标题】:Error cannot read property of undefined using node.js with mysql错误无法使用带有 mysql 的 node.js 读取未定义的属性
【发布时间】:2019-04-11 08:43:34
【问题描述】:

当密码与数据库的内容不匹配时,我不断收到此错误无法读取未定义的属性,但如果密码相同则一切正常。

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()
        }
});

});

如果我输入了错误的密码并且我点击了 else 子句,当我收到错误时我不确定为什么。

【问题讨论】:

  • 您好,这里有一些问题会出现:)。首先,您很容易受到该查询的 SQL 注入攻击。其次,您的 SQL 处理程序是否会抛出空结果?如果不太可能,您需要在尝试访问它的属性之前检查结果是否存在。
  • 这只是一个本地测试脚本,因为我正在学习节点并表达工作,所以 SQL 注入在这里不是一个问题,但我很感激提出它让我知道。返回的结果不为空。

标签: javascript mysql node.js express


【解决方案1】:

看起来变量res 没有在匿名回调函数范围内的任何地方声明。您在 if 条件 result[0].password === req.body.password 中使用 result,但在 if/else 子句中使用 res。尝试使用result 而不是res

【讨论】:

  • 看起来它们是可以互换的,因为改变后的结果是一样的。
猜你喜欢
  • 2013-03-24
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
相关资源
最近更新 更多