POST Request
Let’s create book using the Book model (POST)
Javascript
// Create a new book app.post( '/books' , async (req, res) => { try { const book = new Book(req.body); await book.save(); res.status(201).json(book); } catch (error) { res.status(400) .json({ error: error.message }); } }); |
We’ve implemented try-catch blocks to handle success and error messages. The use of async-await syntax ensures a structured and readable code style, allowing us to seamlessly wait for promises and enhancing error handling. This approach contributes to a cleaner and maintainable codebase for our Books API.
Now add data to the body in postman and send a POST request.
How to Build a RESTful API Using Node, Express, and MongoDB ?
This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building scalable and efficient APIs.
Contact Us