我正在将护照与bookshelf配合使用,在将用户插入数据库时遇到问题。
我正在使用邮递员,它表明已将用户添加到数据库中,但没有添加。
关于书架,护照和postgres一起使用的信息似乎很少。因此,这很难找到这样的解决方案。
路由/用户
router.post('/register', (req, res, next) => {
passport.authenticate('register', (err, user, info) => {
if(err){
console.log(err)
}
if(info !== undefined){
console.log(info.message)
res.status(403).send(info.message)
}else{
req.logIn(user, err => {
const data = {
username: req.body.username.trim(),
password: req.body.password.trim(),
email: req.body.email.trim()
}
console.log(data);
User.forge({
username: data.username
}).fetch().then( (user) => {
console.log('user creatd in db');
res.status(200).send({
message:'user created'
})
})
})
}
})(req, res, next);
});
passport.js
import passport from 'passport';
import LocalStrategy from 'passport-local';
import User from '../models/User';
import bcrypt from 'bcrypt';
import JWTstrag from 'passport-jwt';
import ExtracJWT from 'passport-jwt';
const JWTstrategy = JWTstrag.Strategy
const ExtractJWT = ExtracJWT.ExtractJwt
const Local = LocalStrategy.Strategy
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
secretOrKey: process.env.JWT_SECRET,
};
passport.use('jwt', new JWTstrategy(opts, (jwt_payload, done) => {
try{
User.forge({username: jwt_payload._id})
.fetch()
.then( (user) => {
if(user){
console.log('user found in db in passport');
done(null, user)
}else{
console.log('user not found in db');
done(null, false)
}
})
} catch(err){
done(err)
}
}))
passport.use(
'register',
new Local(
{
usernameField: 'username',
passwordField: 'password',
// passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
try {
User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
if (user != null) {
console.log('username or email already taken');
return done(null, false, {
message: 'username or email already taken',
});
} else {
bcrypt.hash(password, 12).then(hashedPassword => {
const user = new User({
username: req.body.username,
password: hashedPassword,
email: req.body.email
})
user.save().then( () => {
res.status(200).send('user created')
return done(null, user);
})
});
}
});
} catch (err) {
return done(err);
}
},
),
);
// passport.use(new Local ( (username, password, done) => {
// User.findOne({username: username} , (err, user) =>{
// if(err){
// return done(err)
// }
// if(!user){
// return done(null, false, {message: "Incorrect username."})
// }
// if(!user.validPassword(password)){
// return done(null, false, {message: 'Incorrect password'})
// }
// return done (null, user)
// })
// }))
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(user, done) {
User
.forge({id: user})
.fetch()
.then((usr) => {
done(null, usr);
})
.catch((err) => {
done(err);
});
});
main.js
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
import passport from 'passport';
import session from 'express-session';
import './config/passport';
const app = express();
app.use(cors());
app.use(logger('dev'));
// For React Stuff if need be
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(bodyParser.json());
// you need body parser urlencoded so passport will not give a Missing Credentials error
app.use(bodyParser.urlencoded({ extended:false}));
app.use(session({
saveUninitialized: false,
resave:false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
secret : process.env.JWT_SECRET,
}));
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.use('/users', userRoute);
app.use(() => (req, res, next) =>{
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
//build mode
// app.get('*', (req, res) => {
// res.sendFile(path.join(__dirname+'/client/public/index.html'));
// })
// module.parent prevents the
// Node / Express: EADDRINUSE, Address already in use error when unit testing
if(!module.parent){
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);
}
export default app;
答案 0 :(得分:0)
修复后,出现了许多错误。
一个是
完成不是功能
将通过取消注释来解决
passReqToCallback: true,
两个应该不是通行证文件中的资源,而是路由文件。
因此删除
res.status(200).send('user created')
现在一切都应该正常了。
passport.js
passport.use(
'register',
new Local(
{
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
try {
User.forge({username: username}, {email: req.body.email}).fetch().then(user => {
if (user != null) {
console.log('username or email already taken');
return done(null, false, {
message: 'username or email already taken',
});
} else {
bcrypt.hash(password, 12).then(hashedPassword => {
const user = new User({
username: req.body.username,
password: hashedPassword,
email: req.body.email
})
user.save().then( () => {
return done(null, user);
})
});
}
});
} catch (err) {
return done(err);
}
},
),
);
路由/用户
router.post('/register', (req, res, next) => {
passport.authenticate('register', (err, user, info) => {
if(err){
console.log(err)
}
if(info !== undefined){
console.log(info.message)
res.status(403).send(info.message)
}else{
req.logIn(user, err => {
const data = {
username: req.body.username.trim(),
password: req.body.password.trim(),
email: req.body.email.trim()
}
console.log(data);
User.forge({
username: data.username
}).fetch().then( (user) => {
console.log('user creatd in db');
res.status(200).send({
message:'user created'
})
})
})
}
})(req, res, next);
});