I am working on a project and I'm trying to build a login page on nodejs-html by using mysql as database. But my code directly gets to "response.send('Please enter Username and Password!');" part, and shows me that page.(no problem with mysql connection) Why can't i check if the login username and password is right? And go to the next page if true?
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var connection = mysql.createConnection({
....................
});
connection.connect((err) => {
if(err){
throw err;}
else console.log("connected");
});
var app = express();
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/login.html'));
});
app.post('/', function(request, response) {
var username = request.body.user_name;
var password = request.body.pass;
console.log(username);
if (username && password) {
connection.query('SELECT * FROM users WHERE user_name = ? AND pass = ?', [username, password], function(error, results, fields) {
console.log(username);
if (results.length > 0) {
request.session.loggedin = true;
request.session.user_name = username;
response.redirect('/secondPage');
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
});
app.get('/login', 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)
.body.user_name is undefined that's why
您的html中必须具有“忘记名称”属性
输入type =“ text” name =“用户名”
也是密码
<input type="password" name="pass" >
给它们合适的名称属性,以便正文对象可以访问它们