Всякий раз, когда я пытаюсь создать нового пользователя, публикуя следующий контент через Почтальон:
{
"username": "username",
"email": "email@email.com",
"password": "password"
}
я получаю сообщение Bad Request
.
Я настраиваю свой API с помощью : express
, mongoose
и passportjs
как это:
Файл: 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;
Что я делаю не так? Почему появляется это сообщение?
Заранее спасибо!