gpt4 book ai didi

javascript - MEAN 应用程序错误预期对象

转载 作者:可可西里 更新时间:2023-11-01 09:07:00 24 4
gpt4 key购买 nike

我正在尝试编写一个普通的身份验证应用程序。现在我可以通过 postman 在 mongodb 中创建用户但是当我尝试对其进行身份验证时,如果它有错误的用户名或密码,它会提供正确的反馈,错误的密码等,但如果它与数据库中的正确用户名和密码匹配,服务器关闭,它不会对 postman 提供任何反馈,并在服务器终端上给出以下错误:

(node:11262) DeprecationWarning: Mongoose: mpromise (mongoose's 
default promise library) is deprecated, plug in your own promise
library instead: http://mongoosejs.com/docs/promises.html
/home/cagdas/Desktop/basictest/node_modules/jsonwebtoken/sign.js:90
throw err;
^

Error: Expected object
at validate
(/home/cagdas/Desktop/basictest/node_modules/jsonwebtoken
/sign.js:35:11) at Object.module.exports [as sign]
(/home/cagdas/Desktop/basictest/node_modules/jsonwebtoken
/sign.js:101:7) at User.comparePassword
(/home/cagdas/Desktop/basictest/routes/users.js:40:26)
at bcrypt.compare (/home/cagdas/Desktop/basictest/models/user.js:52:6)
at
/home/cagdas/Desktop/basictest/node_modules/bcryptjs/dist
/bcrypt.js:297:21
at /home/cagdas/Desktop/basictest/node_modules
/bcryptjs/dist/bcrypt.js:1353:21
at Immediate.next (/home/cagdas/Desktop/basictest/node_modules
/bcryptjs/dist/bcrypt.js:1233:21)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
at processImmediate [as _immediateCallback] (timers.js:617:5)

这是我的代码:应用程序.js:

const express = require('express') ;
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');


// Connect to Database
mongoose.connect(config.database, { useMongoClient: true });


// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to database '+config.database);
});

// On Error
mongoose.connection.on('error', (err) =>{
console.log('Database error: '+err);
});

const app = express();

const users = require('./routes/users');

// Port Number
const port = 3000;

// Cors Middleware
app.use(cors());

// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));

// Body Parser Middleware
app.use(bodyParser.json());

// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

require('./config/passport')(passport);

app.use('/users', users);

// Index Route
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});

// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});

用户.js:

const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const config = require('../config/database');

// Register
router.post('/register', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});

User.addUser(newUser, (err, user) =>{
if(err){
res.json({success: false, msg:'Failed to register user'});
} else {
res.json({success: true, msg:'User registered'});
}
});
});

// Authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;

User.getUserByUsername(username, (err, user) => {
if(err) throw err;
if(!user){
return res.json({success: false, msg: 'User not found'});
}

User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
const token = jwt.sign(user, config.secret, {
expiresIn: 86400 // 1 day
});

res.json({
success: true,
token: 'JWT ' +token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({success: false, msg: 'Wrong Password'});
}
});
})

});

// Profile
router.get('/profile', (req, res, next) => {
res.send('PROFILE');
});

module.exports = router;

数据库.js:

module.exports = {
database: 'mongodb://localhost:27017/basictest',
secret: '123456789'
}

用户.js:

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config =require('../config/database');

// User Schema
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});


const User = module.exports = mongoose.model('User', UserSchema);


module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}


module.exports.getUserByUsername = function(username, callback){
const query = {username: username}
User.findOne(query, callback);
}

module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
});
});
}


module.exports.comparePassword = function(candidatePassword, hash,
callback){
bcrypt.compare(candidatePassword, hash, (err, isMatch) => {
if(err) throw err;
callback(null, isMatch);
});
}

护照.js

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');


module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload._id, (err, user) => {
if(err){
return done (err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
}

最佳答案

解决方案 - 不仅仅是用户 { data: user }

const token = jwt.sign({data: user}, config.secret, {
expiresIn: 604800 // 1 week
});

关于javascript - MEAN 应用程序错误预期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46115993/

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