我正在尝试写一个关于使用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);
感谢您的帮助。
答案 0 :(得分:0)
您的结果变量似乎未定义。请检查 sql 查询是否没有返回 null。
答案 1 :(得分:0)
错误表明结果未定义。你可以放
console.log(results)
就在 results.length > 0 之前,有条件地查看结果是什么。
答案 2 :(得分:0)
您的代码没有任何错误检查机制,请更新代码以处理 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();
})