私はユーザーにログインするためにエクスプレスポストAPIを使用していますが、問題は以前のポストレスポンスを返します。node.jsポストapiが古いレスポンスを返す
私は何をしているのか分かりません。 私はログインを投稿し、すべての古い応答を取得しています:ここで
は私のapp.js
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var csrf = require('csurf');
// var lusca = require('lusca');
var db = require('./db.config');
var index = require('./routes/index');
var auth = require('./routes/auth');
var users = require('./routes/users');
var admin = require('./routes/admin');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
//this or other session management will be required
app.use(session({
\t secret: 'Qwaszx',
\t resave: true,
\t saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));
/**
* CSRF
*/
// app.use(lusca({
// csrf: true,
// csp: { /* ... */},
// xframe: 'SAMEORIGIN',
// p3p: 'ABCDEF',
// hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
// xssProtection: true,
// nosniff: true,
// referrerPolicy: 'same-origin'
// }));
/**
* CSRF Token
*/
app.use(csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals._csrf = req.csrfToken();
next();
});
/**
* Routes
*/
app.use('/', index);
app.use('/auth', auth);
app.use('/users', users);
app.use('/admin', admin);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
と私のauth.jsルートファイル以下の通りですルートディレクトリの下です時間を私は、サーバーを終了し、それを再起動しないでください。
var express = require('express');
var router = express.Router();
var userModel = require('../model/user.model');
var session = require('express-session');
var auth = require('../middleware');
/**
* Get register API
*/
router.get('/register', auth.Auth, function(req, res, next) {
res.render('auth/register', { title: 'Register a new user' });
});
/**
* Post register API
*/
router.post('/register', auth.Auth, function (req, res, next) {
if(req.body.password === req.body.c_password){ //password match
userModel.create(req.body).then(function (result){//Create user
res.redirect('/auth/login');
}).catch(function (err) {
res.redirect('/auth/register');
});
}
else{
res.redirect('/auth/register');
}
});
/**
* Get login API
*/
router.get('/login', auth.Auth, function (req, res, next) {
res.render('auth/login');
});
/**
* Post login API
*/
router.post('/login', auth.Auth, function (req, res, next) {
userModel.login(JSON.stringify(req.body)).then(function(resp) {
// console.log(resp);
req.session.user = {
user_id : resp.user_id,
user_type : resp.user_type,
};
// res.send(resp);
res.json(resp);
// res.redirect('/auth/login')
}).catch(function (err){
// console.log(err);
res.json(err);
// res.redirect('/auth/login')
});
});
/**
* Logout API
*/
router.get('/logout', function (req, res, next) {
return userModel.logout(req.session.user.user_id).then(function (result) {
// console.log("result = " + result);
delete req.session.user;
res.redirect('/auth/login');
}).catch(function(err){
// console.log(err);
res.redirect('/');
});
});
module.exports = router;
今私はデータベースインタフェースはuser.model.jsで置く私のモデルファイルを以下に示したモデルディレクトリuderです:
var connection = require('../db.config');
var randomstring = require("randomstring");
var passwordHash = require('password-hash');
var q = require('q');
var deferred = q.defer();
model = {};
model.index = index;
model.create = create;
model.show = show;
model.login = login;
model.logout = logout;
model.adminLogin = adminLogin;
module.exports = model;
/**
* Show all users
*/
function index(){
connection.query('SELECT * FROM users as U JOIN logs as L ON U.id = L.user_id WHERE U.user_type != "1" ORDER BY L.id DESC', function(error, response){
if(error) deferred.reject(error);
if(response.length > 0){
// console.log(response);
deferred.resolve(response);
}
else{
deferred.resolve([]);
}
});
return deferred.promise;
}
/**
* Create a new user
*
* @param {*array} data
*/
function create(data){
var hashedPassword = passwordHash.generate(data.password);
var user = {
'email' : data.email,
// 'user_name' : data.user_name,
'mac_add' : data.mac_add,
'password' : hashedPassword,
'verification_code' : randomstring.generate(10),
'_token' : data._csrf,
}
//Check user is already exists or not
connection.query('SELECT * FROM users WHERE email = "' + user.email + '" LIMIT 0,1', function(error, result) {
if(error) {
deferred.reject(error);
}
if(result[0]){
deferred.reject('Email ' + result[0].email + ' is already taken. Please try with another email.');
}
else{
return createUser();
}
});
//Create User
function createUser() {
connection.query('INSERT INTO users SET ? ', user , function (error, response){
if(error) {
console.log(error);
deferred.reject(error);
}
else{
console.log(response);
deferred.resolve(response);
}
});
}
return deferred.promise;
}
/**
* Show user details
*
* @param {*number} id
*/
function show(id){
connection.query('SELECT * FROM users WHERE id = "' + id + '"', function(error, response) {
if(error) deferred.reject(error);
if(response[0]) deferred.resolve(response[0]);
});
return deferred.promise;
}
/**
* Login user using email, password and mac address
*
* @param {* array} data
*/
function login(data){
var userData = JSON.parse(data);
connection.query('SELECT * FROM users WHERE email = "' + userData.email + '" LIMIT 0,1', function(error, response) {
if(error) deferred.reject(error);
//check if user exists
if(response.length > 0){
if(passwordHash.verify(userData.password, response[0].password)){//password matching
// Validate that an address is a mac address
if(response[0].user_type === 0){
console.log(response[0]);
deferred.resolve(response[0]);
// if (require('getmac').isMac(response[0].mac_add)) {
// // var res = JSON.parse(result[0]);
// return createLog(response[0].id, response[0].user_type);
// }
// else{
// deferred.reject('Unauthorized System!');
// }
}
// else{
// var result = {
// 'user_id' : response[0].id,
// 'user_type' : response[0].user_type,
// }
// deferred.resolve(result);
// }
}
else{
deferred.reject('Invalid credential');
}
}
else{
deferred.reject('User not found');
}
});
/**
* Create user logs
*
* @param {*numeric} user_id
*/
function createLog(user_id, user_type){
var log = {
'user_id' : user_id,
// 'in_time' : new Date(),
}
result = {
'user_id' : user_id,
'user_type' : user_type,
}
connection.query('INSERT INTO logs SET ? ', log, function(err, resp) {
if(err) deferred.reject(err);
if(resp) deferred.resolve(result);
});
}
return deferred.promise;
}
/**
* Logout out time entry
*
* @param {*number} user_id
*/
function logout(user_id){
//Get row id of current log from logs table
connection.query('SELECT id FROM logs where user_id = "' + user_id + '" ORDER BY id DESC LIMIT 0,1', function(err, resp){
if(err) deferred.reject(err);
if(resp[0]){
// console.log(result[0].id);
return updateLog(resp[0].id); //updating time
}else{
deferred.reject("No logs");
}
});
function updateLog(id){ // update the out time
// var out_time = new Date();
// console.log(out_time);
connection.query('UPDATE logs SET signature = "shift end", status = "1" WHERE id = ' + id, function(error, response) {
if(error) deferred.reject(error);
if(response) deferred.resolve(response);
});
// console.log(query.sql);
}
return deferred.promise;
}
/**
* Admin Login
*
* @param {*array} data
*/
function adminLogin(data){
var userData = JSON.parse(data);
connection.query('SELECT * FROM users WHERE email = "' + userData.email + '" AND user_type = "1" LIMIT 1', function(error, response) {
if(error) deferred.reject(error);
//check if user exists
if(response.length > 0){
if(passwordHash.verify(userData.password, response[0].password)){//password matching
// console.log("admin response = " + response[0]);
deferred.resolve(response[0]);
}
else{
deferred.reject('Invalid Credential');
}
}
else{
deferred.reject('Unauthorized user');
}
});
return deferred.promise
}
今私は何をしているのかを知りたい。 ノードサーバーを吊り下げてもう一度再起動すると正常に動作しますが、それ以外の場合は同じエラーまたは成功の応答が別の資格情報で返されます。