gpt4 book ai didi

javascript - 使用 NodeJS 设置 session 变量

转载 作者:行者123 更新时间:2023-11-30 15:12:04 26 4
gpt4 key购买 nike

经过身份验证后,我想设置一个 session 变量。目标是访问每个 View 的用户 ID。

我使用 express 和 express-session。我的问题是当我想访问 session 变量时。我没有发现它们是否是在使用它之前要做的初始化。因为当我使用时:

if(req.session.username)

例如,我有一个错误:未定义用户名。

应用程序.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cors=require('cors');

//var index = require('./routes/index');
//var users = require('./routes/users');
var UsersDB=require('./routes/UsersDB');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(cors());
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', index);
//app.use('/users', users);
app.use('/Users',UsersDB);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

app.use(function(req, res, next) {
res.set({'Content-Type': 'text/plain; charset=utf-8;',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'X-PINGOTHER',
'Access-Control-Max-Age': '1728000'});
next();
});

// 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;

用户数据库.js :

var express = require('express');
var router = express.Router();
var Users=require('../models/Users');
var multer = require('multer');
var crypto = require('crypto');

var cookieParser = require('cookie-parser');
var session = require('express-session');

var app = express();

app.use(cookieParser());
app.use(session({
secret: "fd34s@!@dfa453f3DF#$D&W",
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));

var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + ".png")
}
});

var upload = multer({ storage: storage }).single('avatar');

router.post('/login',function(req,res,next)
{
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
return
}
// Everything went fine
console.log(req.body);
var login = req.body.username;
var pass = req.body.password;

if(req.session.username) {
console.log(req.session.username);
}
else{
req.session.username = "toto";
}

const hash = crypto.createHmac('sha256','YouOu').update(pass).digest('hex');
Users.getUsersByEmail(login,function(err,rows)
{
if(rows == null){
res.end("No such user");
return;
}
if(rows[0].password != hash){
res.end("Wrong pass")
return;
}
else{
res.end("Ok")
return;
}
})

})
});

module.exports=router;

登录.html:

<script type="text/javascript">
$("form[name=loginform]").submit(function(event){

//disable the default form submission
event.preventDefault();

//grab all form data
var formData = new FormData($(this)[0]);

$.ajax({
url:'http://localhost:3000/Users/login',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == "Wrong pass") {
alert("wrong password");
} else if(returndata == "No such user")
{
alert("no such user");
} else {
alert("Welcome");
window.location.href="index.html"
}

}
});

return false;
});


</script>

最佳答案

据我所知,问题是您正在 UsersDB.js 中的一个应用程序模块上初始化 session ,该模块将不会被使用。尝试在 app.js 中初始化它。

关于javascript - 使用 NodeJS 设置 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976933/

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