gpt4 book ai didi

javascript - 使用 Passport.js 对用户注册提出错误请求

转载 作者:行者123 更新时间:2023-12-02 21:42:07 24 4
gpt4 key购买 nike

每当我尝试通过 Postman 发布下一个内容来创建新用户时:

{
"username": "username",
"email": "email@email.com",
"password": "password"
}

我收到一条错误请求消息。

我正在使用 expressmongoosepassportjs 设置 API,如下所示:

文件:models/user.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
});

// eslint-disable-next-line func-names
UserSchema.pre('save', async function(next) {
const hash = await bcrypt.hash(this.password, 10);
this.password = hash;
next();
});

// eslint-disable-next-line func-names
UserSchema.methods.isValidPassword = async function(password) {
await bcrypt.compare(password, this.password);
};

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

module.exports = User;

文件:config/passport.js

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const JWTStrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const { JWT_SECRET } = require('./env');

passport.use(
new JWTStrategy(
{
secretOrKey: JWT_SECRET,
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
},
async (token, done) => {
try {
return done(null, token.user);
} catch (error) {
return done(error);
}
},
),
);

passport.use(
'signup',
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
async (email, password, done) => {
try {
const user = await User.create({ email, password });
return done(null, user);
} catch (error) {
return done(error);
}
},
),
);

passport.use(
'login',
new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
async (email, password, done) => {
try {
const user = await User.findOne({ email });
if (!user) {
return done(null, false, { message: 'auth/not-found' });
}

const validPassword = await user.isValidPassword(password);
if (!validPassword) {
return done(null, false, { message: 'auth/wrong-password' });
}

return done(null, user, { message: 'auth/logged-in' });
} catch (error) {
return done(error);
}
},
),
);

文件:router/auth.js

const router = require('express').Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/env');

router.post(
'/signup',
passport.authenticate('signup', { session: false }),
async (req, res) => {
return res.send({
message: 'signup/success',
user: req.user,
});
},
);

router.post('/login', async (req, res, next) => {
// eslint-disable-next-line consistent-return
passport.authenticate('login', async (err, user) => {
try {
if (err || !user) {
const error = new Error('error/occurred');
return next(error);
}

req.login(user, { session: false }, async error => {
if (error) {
return next(error);
}

// eslint-disable-next-line no-underscore-dangle
const body = { _id: user._id, email: user.email };
const token = jwt.sign({ user: body }, JWT_SECRET);

return res.send({ token });
});
} catch (error) {
return next(error);
}
})(req, res, next);
});

module.exports = router;

文件:config/express.js

const express = require('express');
const compression = require('compression');
const cors = require('cors');
const helmet = require('helmet');
const methodOverride = require('method-override');
const morgan = require('morgan');
const { NODE_ENV } = require('./env');
const routes = require('../router');

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

const app = express();

let morganFormat = 'dev';
if (NODE_ENV === 'production') morganFormat = 'combined';

app.use(
morgan(morganFormat, {
skip: (req, res) => res.statusCode < 400,
stream: process.stderr,
}),
);

app.use(
morgan(morganFormat, {
skip: (req, res) => res.statusCode >= 400,
stream: process.stdout,
}),
);

app.use(compression());
app.use(cors());
app.use(helmet());
app.use(methodOverride('X-HTTP-Method-Override'));
app.use('/api', routes);

module.exports = app;

我做错了什么?为什么会出现此消息?

提前致谢!

最佳答案

错误请求通常意味着路由层中的某个地方存在错误。

您正在使用methodOverride ,根据他们的文档,它必须在任何检查方法类型的中间件之前使用,因此在 cors 和 Helm 之后使用它可能是错误配置。

关于javascript - 使用 Passport.js 对用户注册提出错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345106/

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