登录注册和身份验证工作正常但我只是尝试存储离开应用程序数据意味着这是用户输入的简单文本。我想在db mysql中存储当前登录用户名和键入的离开应用程序并向用户显示(前端)。
//App.js
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bcrypt = require('bcrypt-nodejs');
var ejs = require('ejs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// custom libraries
// routes
var route = require('./route');
// model
var Model = require('./model');
var app = express();
passport.use(new LocalStrategy(function(username, password, done) {
new Model.User({username: username}).fetch().then(function(data) {
var user = data;
if(user === null) {
return done(null, false, {message: 'Invalid username or password'});
} else {
user = data.toJSON();
if(!bcrypt.compareSync(password, user.password)) {
return done(null, false, {message: 'Invalid username or password'});
} else {
return done(null, user);
}
}
});
}));
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(username, done) {
new Model.User({username: username}).fetch().then(function(user) {
done(null, user);
});
});
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cookieParser());
//app.use(bodyParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//app.use(session({secret: 'secret strategic xxzzz code'}));
app.use(session({ secret: 'secret strategic xxzzz code', cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
// GET
app.get('/', route.index);
// signin
// GET
app.get('/signin', route.signIn);
// POST
app.post('/signin', route.signInPost);
// signup
// GET
app.get('/signup', route.signUp);
// POST
app.post('/signup', route.signUpPost);
// logout
// GET
app.get('/signout', route.signOut);
// app.get('/Data', route.data);
// 404 not found
app.use(route.notFound404);
var server = app.listen(app.get('port'), function(err) {
if(err) throw err;
var message = 'Server is running @ http://localhost:' + server.address().port;
console.log(message);
});
和
//route.js
var passport = require('passport');
var bcrypt = require('bcrypt-nodejs');
// custom library
// model
var Model = require('./model');
// index
var index = function(req, res, next) {
if(!req.isAuthenticated()) {
res.redirect('/signin');
} else {
var user = req.user;
if(user !== undefined) {
user = user.toJSON();
}
res.render('index', {title: 'Home', user: user});
}
};
// sign in
// GET
var signIn = function(req, res, next) {
if(req.isAuthenticated()) res.redirect('/');
res.render('signin', {title: 'Sign In'});
};
// sign in
// POST
var signInPost = function(req, res, next) {
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/signin'}, function(err, user, info) {
if(err) {
return res.render('signin', {title: 'Sign In', errorMessage: err.message});
}
if(!user) {
return res.render('signin', {title: 'Sign In', errorMessage: info.message});
}
return req.logIn(user, function(err) {
if(err) {
return res.render('signin', {title: 'Sign In', errorMessage: err.message});
} else {
return res.redirect('/');
}
});
})(req, res, next);
};
// sign up
// GET
var signUp = function(req, res, next) {
if(req.isAuthenticated()) {
res.redirect('/');
} else {
res.render('signup', {title: 'Sign Up'});
}
};
// sign up
// POST
var signUpPost = function(req, res, next) {
var user = req.body;
var usernamePromise = null;
usernamePromise = new Model.User({username: user.username}).fetch();
return usernamePromise.then(function(model) {
if(model) {
res.render('signup', {title: 'signup', errorMessage: 'username already exists'});
} else {
var password = user.password;
var hash = bcrypt.hashSync(password);
var signUpUser = new Model.User({username: user.username, password: hash});
signUpUser.save().then(function(model) {
// sign in the newly registered user
signInPost(req, res, next);
});
}
});
};
// sign out
var signOut = function(req, res, next) {
if(!req.isAuthenticated()) {
notFound404(req, res, next);
} else {
req.logout();
res.redirect('/signin');
}
};
var data = function(req, res, next){
if(!req.isAuthenticated()) {
notFound404(req, res, next);
} else {
var leavedata = req.body;
console.log (leavedata);
var userdataPromise = null;
// userdata = new Model.UserData({leavedata: leavedataa.leavedata}).fetch();
// return userdata.then(function (model) {
var userleavedata = new Model.UserDataPromise({username: 'admin', leavedata: leavedata.leavedata });
userleavedata.save().then(function(model){
signin(req, res, next);
});
// });
}
};
// 404 not found
var notFound404 = function(req, res, next) {
res.status(404);
res.render('404', {title: '404 Not Found'});
};
// export functions
// index
module.exports.index = index;
// sigin in
// GET
module.exports.signIn = signIn;
// POST
module.exports.signInPost = signInPost;
// sign up
// GET
module.exports.signUp = signUp;
// POST
module.exports.signUpPost = signUpPost;
// sign out
module.exports.signOut = signOut;
// 404 not found
module.exports.notFound404 = notFound404;
和db.js
//db.js
var knex = require('knex')({
client: 'mysql',
connection: {
host: 'localhost',
user: 'root',
password: '1234',
database: 'employee',
charset : 'utf8'
}
});
var Bookshelf = require('bookshelf')(knex);
module.exports.DB = Bookshelf;
和model.js
//model.js
var DB = require('./db').DB;
var User = DB.Model.extend({
tableName: 'tblUsers',
idAttribute: 'userId'
});
var UserData = DB.Model.extend({
tableName: 'leave_data',
});
module.exports = {
User: User,
UserData: UserData
};
和sechema.sql
//schema.sql
create database if not exists dbUsers;
use dbUsers;
drop table if exists tblUsers;
create table if not exists tblUsers(
userId integer primary key auto_increment,
username varchar(100) unique,
password varchar(100)
)engine=innodb;
create table if not exists leave_data(
username varchar(100),
leavedata varchar(500)
)engine=innodb;
和观点
//signin.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= title %></title>
</head>
<style type="text/css">
img{
width: 100%;
}
h2{
padding: 0 596px;
}
form{
margin-left: 561px;
}
</style>
<body>
<div class = "header">
<img src="http://www.face-9.com/wp-content/uploads/2015/11/railway-
banner.jpg">
</div>
<h2>Sign In Form</h2>
<form method="post" action="/signin">
<% if(typeof(errorMessage) !== 'undefined') {%>
<span><%= errorMessage %></span>
<% } %>
<p>
<label for="username">username</label>
<input type="text" name="username" id="username"
placeholder="username" required="true"/>
</p>
<p>
<label for="password">password</label>
<input type="text" name="password" id="password"
placeholder="password" required="true"/>
</p>
<p>
<input type="submit" name="signin" id="signin" value="sign in"/>
<a href="/signup" title="register">register</a>
</p>
</form>
</body>
</html>
view- signup.ejs
//signup.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= title %></title>
</head>
<body>
<h2>Register Form</h2>
<form method="post" action="/signup">
<% if(typeof(errorMessage) !== 'undefined') {%>
<span><%= errorMessage %></span>
<% } %>
<p>
<label for="username">username</label>
<input type="text" name="username" id="username"
placeholder="username" required="true"/>
</p>
<p>
<label for="password">password</label>
<input type="text" name="password" id="password"
placeholder="password" required="true"/>
</p>
<p>
<input type="submit" name="signup" id="signup" value="register"/>
<a href="/signin" title="sign in">sign in</a>
</p>
</form>
</body>
</html>
view- index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= title %></title>
</head>
<body>
<div class = "header">
<img src="http://www.face-9.com/wp-content/uploads/2015/11/railway-
banner.jpg">
</div>
<p>
Welcome <strong><%= user.username %></strong>
<a href="/signout" title="sign out">sign out</a>
</p>
<form method="post" action="/">
<p>
<label for="leavedata">write your leave application here</label>
<input type="text" name="leavedata" id="leavedata"
placeholder="leavedata" required="true"/>
</p>
<p>
<input type="submit" name= "Data" id="Data" value="submit">
</p>
</form>
</body>
</html>