This project serves as a guide/template for a 3-tier architecture. If you are entirely new to Web Development. I highly suggest you watch this video first. This project contains 2 parts: Built a simple/good structured SERVER App with NodeJS/ExpressJS/MongoDB Built a ReactJS app and integrate it with your SERVER from (1). In this post, I will show you the part to build your first Server API. Here is the final code: https://github.com/calvinqc/calvinqc.com Requirement Node.js npm registry Text Editor: OR …anything you like. VSCode : this will allow you to test your API (GET, POST, PUT, DELETE, etc.) Postman Getting Started Open your Terminal and redirect to the directory where you want to place your project: $ mkdir project && mkdir project/server && mkdir project/client && cd server/ Now, you’re in the Server folder. Create a file and add the below code. package.json $ touch package.json This is where you store all the project dependencies, and scripts to start your application { : , : , : , : { : , : }, } "name" "server" "version" "1.0.0" "private" true "scripts" "start" "node -r esm app.js" "dev" "nodemon -r esm app.js" Install 1. ESLint Airbnb Install to allow all developers to have the same coding style and follow a right Javascript coding style ESLint Airbnb $ npx — dev eslint- -airbnb install-peerdeps config Create in your project and add this: .eslintrc { : } "extends" "airbnb" 2. Babel Install : This compiles ES6 to ES5 to compress the project size when pushing to production to reduce run-time and because many web browsers can only read ES5. Babel $ npm esm — save-dev install babel-cli babel-register babel-preset-es2015 babel-preset-stage-2 babel-core babel-polyfill Create file in your server project and add this: .babelrc { : [ , ] } "presets" "es2015" "stage-2" 3. Express Middleware Install the first 3 middlewares to run your App: $ npm i — esm nodemon save express : an essential framework for NodeJS to start a server project. Express This goes with `babel` and allows you to run ES6. esm : This is my favorite; it will enable you to restart the server automatically whenever you make changes in the server. nodemon : Build your Server The first step is to create a file that will contain our code for Node.js Server $ touch app.js This will start a server on and initialize all the dependencies that your app requires. Add this simple code to app.js app.js PORT 8080 express ; app = express(); app.get( , (req, res) => { res.status( ).json({ : }); }); app.listen( , () => { .log( ); }); // Import all dependencies & middleware here import from 'express' // Init an Express App. This later starts a server and put all dependencies into your project to use const // Use your dependencies here // use all controllers(APIs) here '/' 200 status 'success' // Start Anything here 8080 console 'Example app listening on port 8080!' Start your Server You can find the script that runs these functions in package.json $ npm start OR (To run automatically whenever you make a new change, run used by ) nodemon $ npm run dev Use Dependencies/Middleware Express is a framework, but it doesn’t mean that it contains all you need to make a great web app. Then, you’ll need to import more powerful libraries. An example: Install : body-parser $ npm i body-parser Import this to : app.js bodyParser ; app.use(bodyParser.urlencoded({ : })); app.use(bodyParser.json()); import from 'body-parser' // Use your dependencies here extended false Create RESTful APIs Now, your project is getting complicated, and you don’t want to put all your API into , which is used only for starting & initializing your app. app.js You want to separate your APIs into different folders. Run the following commands: $ mkdir controller $ touch controller/index.js && touch controller/user.controller.js Open your and import this code in there: user.controller.js express ; userController = express.Router(); userController.get( , (req, res) => { res.status( ).json({ : }); }); userController; import from 'express' const '/' 200 status 'success' export default Express Router is a class which helps us to create router handlers. It also can extend this routing to handle validation, handle 404 or other errors, etc. Scalability Assume your project has many controllers. You don’t want to keep importing all controllers to your . Then, you want to use 1 file to import all controllers. app.js Open in your controller and import this: index.js userController ; { userController, }; import from './user.controller' //import abcController from './abc.controller'; //import xyzController from './xyz.controller'; export //abcController, //xyzController Right now, you only have userController, but if you have more controllers, un-comment the import and export. NOTE: the comments are just examples. Adding API to Express App You just created the Controller, but you haven’t told Express App to it. use In , first import Controllers: app.js { userController, } ; import from './controller' Replace this: app.get( , (req, res) => { res.status( ).json({ : }); }); '/' 200 status 'success' with this: app.use( , userController); '/' // Uncomment and modify the route if you want to use any controllers //app.use('/abc', abcController); //app.use('/xyz', xyzController); Database You can choose any Database Language to learn and apply. In this project, I will use as it has an excellent library to interact with NodeJS. MongoDB Install & Start MongoDB You will need to install : “Mongoose provides a straight-forward, schema-based solution to model your application data.” Mongoose Open a terminal: new $ brew update $ brew tap mongodb/brew $ brew install mongodb-community@ 4.2 Open your previous terminal: $ npm i mongoose Connection In your , import mongoose: app.js bodyParser ; mongoose ; import from 'body-parser' import from 'mongoose' And connect MongoDB in : app.listen() app.listen( , () => { .log( ); mongoose.connect( ).then( { .log( ); }); }); 8080 console `Started successfully server at port ` ${port} 'mongodb://localhost/test' => () console `Conneted to mongoDB at port 27017` Schema $ mkdir database && mkdir database/models && mkdir database/schemas $ touch database/schemas/user.schema.js $ npm i sha256 First, create the schema, and initialize all the attributes for that object in the database. For example, the schema will have two attributes: & . User email hashedPassword Open : user.schema.js { Schema } ; sha256 ; userSchema = Schema({ : { : , : }, : { : , : }, }); userSchema.methods.comparePassword = { .hashedPassword === sha256(password); }; userSchema import from 'mongoose' import from 'sha256' const new hashedPassword type String required true email type String required true /** * @param {*} password */ ( ) function comparePassword password return this export default Models Then, you want to create a model for that each schema you create and add them into (so you only need to call one file): index.js touch database/ /user. .js $ models model Open : user.model.js mongoose ; userSchema ; User = mongoose.model( , userSchema); User; import from 'mongoose' import from '../schemas/user.schema' const 'User' export default Open : models/index.js User ; { User, }; import from './user.model' export Save data using API Open . controller/user.controller.js Import User & with these 2 new APIs(Endpoints): replace userController.get(‘/’, …) { User } ; sha256 ; userController.get( , (req, res) => { User.find({}, (err, result) => { res.status( ).json({ : result, }) }) }); userController.post( , (req, res) => { { email, password } = req.body; userData = { email, : sha256(password) } newUser = User(data); newUser .save() .then( { res.status( ).send(data); }) .catch( { res.status( ).send( ); }); }); import from '../database/models' import from 'sha256' /** * GET/ * retrieve and display all Users in the User Model */ '/' 200 data /** * POST/ * Add a new User to your database */ '/add-user' const const hashedPassword const new => data 200 => err 400 "unable to save to database" Starting Start Database: $ mongod -config /usr/ /etc/mongod.conf local Start server $ npm start Postman Open Postman, if you don’t know how to use it. Please watch this tutorial: Use POST/ method and enter . This will call the “/add-user” API. localhost:8080/add-user Add this to your body (Postman), If you don't know where to put this. Please watch the video first. { : , : } 'email' 'calvin.nvqc@gmail.com' 'password' '123456789' Check if your user data is saved to the database, open Web Browser and enter localhost:8080/ Now, you’re done! Congratulations on building your first API. Project Structure project ├── client └── server └── controller - Storing APIs of the app (GET, POST, PUT, DELETE) ├── index.js └── user.controller.js └── database ├── model - store all the models of the project └──schema - create attribute each model ├── global.js - storing your configuration attribute ├── .eslintrc - config ESLint Airbnb Coding Style ├── .babelrc - migrate ES6 -> ES5 to run on different browsers ├── package.json - config ESLint Airbnb Coding Style └── App.js - Everything a server needs to start for