Я работаю над REST API, у меня есть пользовательский маршрут и CRUD, выполненные с уровнем аутентификации с использованием паспорта и JWT. Все происходит идеально, однако, если вы создаете другой маршрут и также должны использовать паспорт js, я не знаю почему, тело запроса становится пустым.
Это происходит, даже если я копирую работающий маршрут пользователя и меняйте только названия вещей в нем, он поставляется с пустым телом запроса !!!
сервер. js
const express = require("express");
const cors = require("cors"); //segurança
const routes = require("./routes/routes");
//iniciando o server
const server = express();
server.use(express.json()); //to be able to use json
//server.use(bodyParser.urlencoded({ extended: false }));
//server.use(bodyParser.json());
//routes
server.use("/api/v1", routes);
//segurança
server.use(cors());
server.listen(3333);
пользователь. js
const express = require("express");
const userRoutes = express.Router();
//auth
const passport = require("passport");
//controller
const UserController = require("../controllers/userController");
//helpers
const { validate, schemas } = require("../helpers/validation");
//controller
userRoutes.get(
"/users",
passport.authenticate("jwt", { session: false }),
UserController.index
);
//signup route POST
userRoutes.post(
"/users/signup",
validate(schemas.userSignUpSchema),
UserController.signUp
);
//signin route POST
userRoutes.post(
"/users/signin",
validate(schemas.userSignInSchema),
passport.authenticate("local", { session: false }),
UserController.signIn
);
//get single user by id
userRoutes.get(
"/users/:id",
passport.authenticate("jwt", { session: false }),
UserController.show
);
// update single user by id
userRoutes.put(
"/users/:id",
passport.authenticate("jwt", { session: false }),
UserController.update
);
//delete sigle user by id
userRoutes.delete(
"/users/:id",
passport.authenticate("jwt", { session: false }),
UserController.destroy
);
module.exports = userRoutes;
маршруты. js
const express = require("express");
const router = express.Router();
const passportConfig = require("../auth/passport");
//const productRoutes = require("../lixo/products");
const userRoutes = require("./user");
//routes
//router.use(productRoutes);
router.use(userRoutes);
router.use(aboutRoutes);
//hendler errors
router.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
router.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
path: req.headers.host + req.baseUrl + req.url
}
});
});
module.exports = router;
userController. js
const JWT = require("jsonwebtoken");
const User = require("../models/user");
// formating the response to the json API pattern
const { jsonApiTransform, checkAdminFromToken } = require("../helpers/helpes");
const { JWT_SECRET } = require("../config");
signToken = user => {
return JWT.sign(
{
iss: "MeGASAUDE-API",
sub: user.id,
admin: user.admin,
iat: new Date().getTime(),
exp: new Date().setDate(new Date().getDate() + 1)
},
JWT_SECRET //should be hashed string to encode ower jwt
);
};
module.exports = {
async signIn(req, res) {
const token = signToken(req.user);
res
.status(200)
.json(jsonApiTransform(req.user, "User", "user signed in", token));
},
async signUp(req, res) {
console.log(req.body);
const {
name,
surname,
email,
phone,
password,
companyName,
description,
admin,
user_img
} = req.value.body;
//check if user exist
const userExists = await User.findOne({ email });
//if so send a error
if (userExists) {
return res
.status(409)
.json(jsonApiTransform(userExists, "User", "user already exists"));
}
//ceate a user
try {
const user = await User.create({
email,
name,
surname,
password,
phone,
companyName,
description,
admin,
user_img
});
//response with yoken
const token = signToken(user);
return res
.status(201)
.json(jsonApiTransform(user, "User", "user create", token));
} catch (err) {
return res.status(400).json({
"error message": "Error on creating user",
"error description": err.message
});
}
},
//index all users
async index(req, res) {
try {
checkAdminFromToken(req.headers.authorization);
const users = await User.find();
return res.json(users.map(user => jsonApiTransform(user, "User", "")));
} catch (err) {
return res.status(400).json({
"error message": "error on show users",
"error description": err.message
});
}
},
//sahow a single user by id
async show(req, res) {
try {
const user = await User.findById(req.params.id);
if (user == null) throw new Error("");
checkAdminFromToken(req.headers.authorization);
return res.status(200).json(jsonApiTransform(user, "User", "user found"));
} catch (err) {
return res.status(404).json({
"error message": "user not found",
user: req.params.id,
"error description": err.message
});
}
},
//upadte a user by id
async update(req, res) {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, {
new: true,
useFindAndModify: false
});
if (user == null) throw new Error("");
checkAdminFromToken(req.headers.authorization);
//response
return res
.status(200)
.json(jsonApiTransform(user, "User", "user updated"));
} catch (err) {
return res.status(404).json({
"error message": "user not found",
user: req.params.id,
"error description": err.message
});
}
},
// delete a user by id
async destroy(req, res) {
try {
const deletedUser = await User.findByIdAndRemove(req.params.id);
if (deletedUser == null) throw new Error("");
checkAdminFromToken(req.headers.authorization);
return res
.status(200)
.json(jsonApiTransform(deletedUser, "User", "user deleted"));
} catch (err) {
return res.status(404).json({
"error message": "user not found",
user: req.params.id,
"error description": err.message
});
}
}
};
, паспорт. js
const passport = require("passport");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const LocalStrategy = require("passport-local").Strategy;
const { JWT_SECRET } = require("../config");
const User = require("../models/user");
//JWT Strategy
passport.use(
new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromHeader("authorization"),
secretOrKey: JWT_SECRET
},
async (payload, done) => {
try {
//find the user specified in token
const user = User.findById(payload.sub);
//if user dont exists handle it
if (!user) {
return done(null, false);
}
//otherwise return the user
done(null, user);
} catch (error) {
done(error, false);
}
}
)
);
// Local Strategy
passport.use(
new LocalStrategy(
{ usernameField: "email" },
async (email, password, done) => {
try {
//find the user given the email
const user = await User.findOne({ email });
//if not handle it
if (!user) {
return done(null, false);
}
//check if password is correct
const isMatch = await user.isValidPassword(password);
//if not handle it
if (!isMatch) {
return done(null, false);
}
//otherwise return the user
done(null, user);
} catch (error) {
done(error, false);
}
}
)
);