About Lesson
In this part of the video, I’ve created an API using Node.js Express server with a MongoDB connection. Then created necessary models, routes and controllers in order to handle CRUD operations.
- root
- models
- User.model.js
- Video.model.js
- Comment.model.js
- routes
- auth.js
- users.js
- videos.js
- comments.js
- controllers
- auth.controller.js
- user.controller.js
- video.controller.js
- comment.controller.js
- models
As you realize, there is an additional route and controller to take care of user authentication. To provide a security I’ve used bcryptjs and JWT library with cookies in the auth controller.
export const signin = async (req, res, next) => { try { const user = await User.findOne({ name: req.body.name }); if (!user) return next(createError(404, "User not found!")); const isCorrect = await bcrypt.compare(req.body.password, user.password); if (!isCorrect) return next(createError(400, "Wrong Credentials!")); const token = jwt.sign({ id: user._id }, process.env.JWT); const { password, ...others } = user._doc; res .cookie("access_token", token, { httpOnly: true, }) .status(200) .json(others); } catch (err) { next(err); } };
And finally, I've combined the API with the UI Design in order to make the application dynamic. To fetch data and make other API requests axios was used and to handle state management, I preferred using redux-toolkit.