gpt4 book ai didi

javascript - node.js post api 返回旧响应

转载 作者:搜寻专家 更新时间:2023-11-01 00:05:07 27 4
gpt4 key购买 nike

我正在使用 express post 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({
secret: 'Qwaszx',
resave: true,
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 路由文件在 routes 目录下,如下所示:我一直在发布登录名并获得旧响应的地方我不退出服务器并重新启动它。

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;

现在我放置数据库接口(interface)的模型文件是 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
}

现在我想知道我做错了什么。如果我挂起 Node 服务器并再次重新启动它,那么它可以正常工作,否则它会使用不同的凭据返回相同的错误或成功响应。

谢谢

最佳答案

谢谢罗伯特,您的回答完全正确。非常感谢。解决方案是为每个功能做出单独的 promise 。

我使用的是 deferred = q.defer();在页面顶部作为全局

所以我必须从这里删除它并将它单独放在每个函数中。

喜欢

function index(){

deferred = q.defer();
....
......
return deferred.promise;
}

这是正确的解决方案,非常感谢罗伯特

谢谢

关于javascript - node.js post api 返回旧响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46273028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com