I just have a small task to do
I want that when I create a post that the user is read from my token
create Function:
exports.create = async (req, res) => {
const user = req.token;
const users = await User.findOne({ userID: user });
const { forumName, forumDescription } = req.body;
const errors = [];
if (!forumName) {
errors.push({ text: "Please Write a Title." });
}
if (!forumDescription) {
errors.push({ text: "Please Write a Description" });
}
if (errors.length > 0) {
res.render("forum/", {
errors,
forumName,
forumDescription,
});
} else {
const newForum = new Forum({ forumName, forumDescription });
newForum.createdBy = users;
await newForum.save();
res.status(201).json(newForum);
}
};
How I create a Post
###
POST http://localhost:8080/forum/
Authorization: Bearer {Token}
Content-Type: application/json
{
"forumName": "test",
"forumDescription": "test"
}
How I search after
exports.get = async (req, res, next) => {
const { userID } = req.body;
try {
const forum = await Forum.findById(userID);
res.status(200).json(forum);
} catch (error) {
error.status = 400;
next(error);
}
};
The problem is I know userID is wrong I don´t know how to solve it
let reqToken = req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer' ? return req.headers.authorization.split(' ')[1] : '';
if(reqToken)
console.log(req.headers.authorization.split(' ')[1]) // will print your header token
else
return res.status(400).send('Unauthorized');
Better way would be to wrap inside a function and handle based on return value.