- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 Passport 身份验证,提交并通过所有验证后,在 successRedirect 上,应用程序不会重定向到指定的路由,而是只是加载,一段时间后它崩溃了。我正在关注 Max S. 的 YouTube 教程,在这里,我将加载我的 passport.js
、我的 index.js
和我的 app.js
有 express 进口。
这里是 PASSSPORT.JS
var passport = require("passport");
var User = require("../models/user");
var LocalStrategy = require("passport-local").Strategy; //chaining the object `Strategy`
//this function tells passport how to store the user in the session
passport.serializeUser(function(user, done) {
done(null, user.id); //whenever you want to store user in your session, serialize it by id (hence `user.id`)
});
passport.deserializeUser(function(id, done) {
//use mongo method to find by id
User.findById(id, function(err, user) {
done(err, user); //when using `done`, return err (first) if unsuccessful or the user if successful
});
});
//----- were not creating a new user yet...
//below we create a new user with a local strategy
//`use` is a passport method that takes the first string argument as the name of the local strategy (below: `local-signup`), and new LocalStrategy takes two argument 1. an object configuration and 2. a call back function
passport.use(
"local-signup",
new LocalStrategy(
{
//object configuration
usernameField: "email", //tell passport that usernameField is email
passwordField: "password", //tell passport that passwordField is password
passReqToCallback: true //which means that in the callback function below you can access and use the (request, email, password and done)
},
function(req, email, password, done) {
//the call back function
//check for validations here, before running the query to database.
req
.checkBody("email", "invalid email")
.notEmpty()
.isEmail();
req
.checkBody("password", "invalid password")
.notEmpty()
.isLength({
min: 4
});
var errors = req.validationErrors();
console.log("req.validationErrors() 44 >>>> ", errors);
if (errors) {
var messages = [];
errors.forEach(function(errors) {
messages.push(errors.value + "" + errors.msg);
console.log("messages here >>>>> ", messages)
});
return done(null, false, req.flash("error", messages));
}
//use mongo method to find one (which is email)
User.findOne({
'email': email,
function(err, user) {
//equal to the second argument passed in the call back function
if (err) {
//check1
console.log("ERROR HERE passport 59 >>>>>>");
return done(err);
}
if (user) {
console.log("USER HERE >>>>>>>");
//in the next line of code:
//null -> means no error but also
//false -> means the process is unsuccessful
//message -> tells user email is already taken
return done(null, false, {
messages: "Email is already in use!"
}); //check2
}
//after passing both checks above, we can create a NEW USER
var newUser = new User();
newUser.email = email;
newUser.password = newUser.encryptPassword(password); //in user.js (under model folder, we implement bcrypt-nodejs hashing capability)
newUser.save(function(err, result) {
//we will save the newUser
if (err) {
//check1
return done(err);
} else {
return done(null, newUser);
}
});
}
});
}
)
);
HERES INDEX.JS(我的路线)
var express = require('express');
var router = express.Router();
var csrf = require('csurf'); //import protection to hashed password
var csrfProtection = csrf(); //initiate it here like a middleware
router.use(csrfProtection);
var passport = require('passport');
// var passport = require("../config/passport");
var Product = require("../models/product");
/* GET home page. */
router.get('/', function(req, res, next) {
//were referencing model here and using `find()` method to query the database
Product.find(function(err, prod){
if (err) {
//check1
return done(err);
}
var productChunks = []; //were gonna render this array below, in our HOOK, as a key in our hbs page
var chunksPerRow = 3;//just to say, we want each row to contain three cards/container
//here we loop through prod
for (var i = 0; i < prod.length; i += chunksPerRow) {// i is incremented by three
productChunks.push(prod.slice(i, i + chunksPerRow)) // logic for keeping each row at three chunks
}
res.render("shop/index", {
title: "Shopping Cart",//hook
products: productChunks//hook
});
});
});
//create our signup route (get)
router.get('/user/signup', function(req, res, next){
//using flash messages after validation is complete
var throwMessage = req.flash('error');
res.render('user/signup', {csrfToken: req.csrfToken(), messages: throwMessage, hasErrors: throwMessage.length>0}) // this is being handled by the csurf package
})
//passport doesnt know the authenticate method because its not imported in this file
//you can import passport here, OR you can require config/passport in the app.js
router.post('/user/signup', passport.authenticate('local-signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}))
router.get('/user/profile', function(req, res, next){
res.render('user/profile');
})
module.exports = router;
这里有我的 APP.JS
// import { extname } from 'path';
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session')//to use csurf you need session installed
var passport = require('passport');
var flash = require('connect-flash');
var validator = require('express-validator');
//route
var indexRouter = require("./routes/index");
var app = express();
//mongoose connect method
//expects an input, which is the path of the server, you can check it after you ran mongod
//the `/shopping` is the name of the database you intend to create
mongoose.connect("mongodb://localhost:27017/shopping");
//require helper -> config/passport here after mongoose connect
require('./config/passport')
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'})) //extname helps identify the name of the files in view folder as `.hbs`
app.set('view engine', '.hbs');//this refers to the engine above '.hbs'
app.use(logger('dev'));
app.use(express.json());
// parse urlencoded request bodies into req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(validator());
app.use(cookieParser());
app.use(session({secret:'mysecret', resave: false, saveUninitialized: false}));//session initialized
//resave = true, session will be saved on a server on each request no matter it saved or not - depracated
//saveUninitialized = true, the essions will be saved even if its not intialized - depracated
//add flash and passport after session secret is initialized ORDER MATTERS
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
这里是我的包 JSON
{
"name": "shopping-cart",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"body-parser": "^1.18.2",
"connect-flash": "^0.1.1",
"cookie-parser": "~1.4.3",
"csurf": "^1.9.0",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-handlebars": "^3.0.0",
"express-session": "^1.15.6",
"express-validator": "^5.0.3",
"hbs": "~4.0.1",
"http-errors": "~1.6.2",
"mongoose": "^5.0.12",
"morgan": "~1.9.0",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"session": "^0.1.0"
}
}
提前致谢! heres the tutorial link我很想完成本教程,但我坚持在注册后单击提交,它不会重定向(即使在通过验证之后)。谢谢!
最佳答案
在 Passport.js 第 45、46 行中输入 User.findOne({ 'email': email, ..... 错误 ис 是 User.findOne({ 'email': email}, .... you电子邮件后缺少括号,然后检查函数中从第 32 行到结束的所有括号
关于javascript - Passport 、蒙戈、 express 、购物车教程在发布请求后点击提交时滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49591183/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!