gpt4 book ai didi

javascript - Passport 、蒙戈、 express 、购物车教程在发布请求后点击提交时滞后

转载 作者:行者123 更新时间:2023-12-03 02:10:33 25 4
gpt4 key购买 nike

我使用 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/

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