RESTful APIs with Node.js and Express
- use
npm install express --save
- use
npm install mongoose --save
- use
npm install nodemon --save
- We are using Babel to trspile ES6 javascript code
- We will require to install Babel BabelPreset2015 and BabelPresetStage0
- We will install it as a devDependency
- use
npm install --save-dev babel-cli babel-preset-es2015 babel-preset-stage-0
- use
npm install body-parser --save
- Write basic code to get started using express app and serve the basic server
|-- src |-- controllers +-- crmController.js |-- models +-- crmModel.js |-- routes +-- crmRoutes.js
- i.e.
GET
,POST
,PUT
,DELETE
- Create Mongoose connection to MongoDB database
- mongoose is an elegant
mongodb
object modeling fornode.js
- Add
body-parser
(Node.js
body parsing middleware.) configs - It used to parse incoming request bodies in a middleware before your handlers, available under the
req.body
property.
- We can define property name and it's
type
along with the field type if required or not. - We can also set default value to the property
- Create
addNewContact
function inside yourcrmController.js
. - The controller will be used to insert data into MongoDB database using the Model we created.
- Replace the
/contact
route'sPOST
method with theaddNewContact
controller and test it out.
- Create
getContacts
function inside yourcrmController.js
. - The controller will be used to fetch data from MongoDB database.
- Replace the
/contact
route'sGET
method with thegetContacts
controller and test it out.
- Create
getContactWithID
function inside yourcrmController.js
. - The controller will be used to fetch a particular data from MongoDB database using a user's ID.
- Add a new
GET
method to this route/contact/:contactId
and pass thegetContactWithID
controller and test it out. - Make sure you pass proper ID from the database example -
localhost:3000/contact/5cad9c9b02825c3294a6be42
- Create
updateContact
function inside yourcrmController.js
. - The controller will be used to update a particular user's data from MongoDB database using a user's ID.
- Update
PUT
method of this route/contact/:contactId
and pass theupdateContact
controller and test it out. - Make sure you pass proper ID from the database example -
localhost:3000/contact/5cad9c9b02825c3294a6be42
and pass data asx-www-form-urlencoded
- Create
deleteContact
function inside yourcrmController.js
. - The controller will be used to delete a particular user's data from MongoDB database using a user's ID.
- Update
DELETE
method of this route/contact/:contactId
and pass thedeleteContact
controller and test it out. - Make sure you pass proper ID from the database example -
localhost:3000/contact/5cad9c9b02825c3294a6be42
and make sure the request type is set toDELETE
- Finally the CRUD operation on this project are completed
- Feel free to make your own routes and add controllers and create new Schema according to your needs