开发者问题收集

如何修复 TypeError: 无法读取未定义的属性“length”?NodeJs

2021-06-10
1955

我正在尝试编写一个关于使用 node js 登录的网站,但我不知道如何解决这个问题。如果你不介意的话。你能为我解释一下这些错误吗?

我的错误

"TypeError: Cannot read property 'length' of undefined"

我的代码

var mysql = require('mysql');
const express = require('express');
var session = require('express-session');
var path = require('path');

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'nodelogin'
});

var app = express();

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}))

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/login.html'))
})

app.post('/auth', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
        connection.query('SELECT * FORM accounts where username = ? AND password = ?', [username, password], function(error, results, fields) {
            if (results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('/home')
            } else {
                response.send('Incorrect Username or Password');
            }
            response.end();
        })
    } else {
        response.send('Please enter Username and Password!');
        response.end();
    }
})

app.get('/home', function(request, response) {
    if (request.session.loggedin) {
        response.send('Welcome back, ' + request.session.username + '!');
    } else {
        response.send('Please login to view this page')
    }
    response.end();
});

app.listen(3000);

谢谢你的帮助。

3个回答

您的结果变量似乎未定义。请检查 SQL 查询是否未返回 null。

Harkirat singh
2021-06-10

错误表明未定义 results。您可以在 results.length > 0 条件之前放置 console.log(results) 来查看 results 是什么。

AS10
2021-06-10

您的代码没有任何错误检查机制,请更新代码以处理 MySQL 包发送的任何错误

connection.query('SELECT * FORM accounts where username = ? AND password = ?', [username, password], function(error, results, fields) {
   if (error) {
       // You need to check this error
       console.log(error);
       response.send('Some Error has occurred');
       return;
   }
   if (results.length > 0) {
       request.session.loggedin = true;
       request.session.username = username;
       response.redirect('/home')
    } else {
       response.send('Incorrect Username or Password');
    }
   response.end();
})

Amir Saleem
2021-06-10