{"id":19606738,"url":"https://github.com/learnwithfair/node-express-documentation","last_synced_at":"2026-04-18T10:36:16.951Z","repository":{"id":236448835,"uuid":"792633204","full_name":"learnwithfair/node-express-documentation","owner":"learnwithfair","description":"node-express-documentation with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]","archived":false,"fork":false,"pushed_at":"2024-05-02T16:37:32.000Z","size":305,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-26T06:23:41.699Z","etag":null,"topics":["documentation","expressjs","learnwithfair","mern","nodejs","rahatul-rabbi","web-development"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/learnwithfair.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-04-27T05:54:52.000Z","updated_at":"2024-05-02T17:12:57.000Z","dependencies_parsed_at":"2025-01-10T08:33:10.643Z","dependency_job_id":null,"html_url":"https://github.com/learnwithfair/node-express-documentation","commit_stats":null,"previous_names":["learnwithfair/node-express-documentation"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/learnwithfair/node-express-documentation","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fnode-express-documentation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fnode-express-documentation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fnode-express-documentation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fnode-express-documentation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learnwithfair","download_url":"https://codeload.github.com/learnwithfair/node-express-documentation/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learnwithfair%2Fnode-express-documentation/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31966201,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T00:39:45.007Z","status":"online","status_checked_at":"2026-04-18T02:00:07.018Z","response_time":103,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["documentation","expressjs","learnwithfair","mern","nodejs","rahatul-rabbi","web-development"],"created_at":"2024-11-11T10:07:04.796Z","updated_at":"2026-04-18T10:36:16.928Z","avatar_url":"https://github.com/learnwithfair.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"## EXPRESS-JS DOCUMENTATION\n\nThanks for visiting my GitHub account!\n\n\u003cimg src =\"https://ajeetchaulagain.com/static/7cb4af597964b0911fe71cb2f8148d64/87351/express-js.png\" height = \"200px\" width = \"200px\"/\u003e **Express-js**, or simply **Express**, is a back end web application framework for building RESTful APIs with Node.js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js. [more](https://www.geeksforgeeks.org/express-js/)\n\n## Source Code (Download)\n\n[Click Here](https://mega.nz/folder/RGFiUApD#PoKIVCwF8IkQhE2PHw1XxQ)\n\n## Required Software (Download)\n\n- VS Code, Download -\u003ehttps://code.visualstudio.com/download\n- Node, Download-\u003e https://nodejs.org/en/download\n- MongoDB Shell(msi) , Download-\u003e https://www.mongodb.com/try/download/shell\n- MongoDB Compass (msi), Download-\u003e https://www.mongodb.com/try/download/community\n- Postman, Download-\u003e https://www.postman.com/downloads/\n\n**Or Online Database (MongoDB Atlas)**\n\n- Register -\u003e https://www.mongodb.com/cloud/atlas/register\n\n## ========== Environment Setup ==========\n\n1. Install Node.js\n2. To verify installation into command form by node -v\n3. For initialization npm write the query in the command window as npm init -y\n4. Setup the opening file into the package.json and change the file with main:'server.js'\n5. To create a server using the express package then write a query into the command window as npm install express.\n   Write code in the server file for initialization\n   const express = require(\"express\");\n   const app = express();\n   app.listen(3000, () =\u003e {\n   console.log(\"Server is running at http://localhost:3000\");\n   });\n\n6. Install the nodemon package for automatically running the server as- npm i --save-dev nodemon (For Developing purpose)\n7. setup the package.json file in the scripts key, write\n   \"scripts\": {\n   \"start\": \"node ./resources/backend/server.js\",\n   \"dev\": \"nodemon ./resources/backend/server.js\",\n   \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\"\n   },\n8. use the Morgan package for automatic restart. Hence install the morgan package as npm install --save-dev morgan (Development purpose)\n   Write code in the server file for initialization\n   const morgan = require(\"morgan\");\n   app.use(morgan(\"dev\")); --\u003e Middlewire.\n9. Install Postman software for API testing by the URL endpoint.\n10. Install Mongobd + MongobdCompass and Mongoshell (For Database)\n\n## ========== Connect MongoDB Database ==========\n\n1. Install Mondodb + Mongodb Compass and Mongodb Shell download from the google.\n2. Set up Environment Variable in drive:c/program file\n3. Create a directory in the base path of the c drive named data. Inside the data directory create another folder db.\n4. Write the command in the CMD window as Mongod. And write the other command in the other CMD window as mongosh.\n5. Then Check the version as mongod --version and mongosh --version.\n6. Install mongoose package as npm i mongoose\n7. Create an atlas account. In the atlas account create a cluster that have a user(as atlas admin) and network access with any access IP address.\n8. Connect the database using URL from the atlas cluster or local Mongodb compass using the mongoose package as mongoose. connect('mongodb://localhost:27017/database-name);\n\n## Mistakes\n\n|                          |                          |\n| :----------------------: | :----------------------: |\n| ![roadmap](images/0.jpg) | ![roadmap](images/1.jpg) |\n| ![roadmap](images/2.jpg) | ![roadmap](images/3.jpg) |\n| ![roadmap](images/4.jpg) | ![roadmap](images/5.jpg) |\n| ![roadmap](images/6.jpg) | ![roadmap](images/7.jpg) |\n\n|                                    |\n| :--------------------------------: |\n| ![roadmap](images/simple-code.jpg) |\n\n## Total Chapters are following\n\n2. Express.js\n   1. introduction to express.js\n   2. express server\n   3. http methods and postman\n   4. Express Router\n   5. HTTP Response\n   6. HTTP Request part-1\n   7. HTTP Request part-2\n   8. HTTP Request part-3\n   9. send and receive from data\n   10. Area Calculator\n   11. How to set .env variables\n   12. Middlewares\n   13. express static Middlewares\n   14. MVC pattern\n\n## Chapter 2: Express.js\n\n### [2.1 Introduction to express.js](https://youtu.be/1Max9huISzA)\n\n- always check the documentation of [express.js](https://www.npmjs.com/package/express)\n- Express.js is a node.js framework which makes life easier\n- no more hassle of setting Content-Type\n- easy to learn and time saving facilitites available because we have ready made stuff in express.js\n- MERN Stack, NERD stack, PERN stack\n\n### [2.2 creating express server](https://youtu.be/t9GVn5j1Hsw)\n\n- first initialize npm : `npm init -y`\n- install express: `npm install express`\n- example\n\n  ```js\n  const express = require(\"express\");\n\n  const PORT = 3000;\n\n  const app = express();\n\n  app.get(\"/\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to express server \u003c/h1\u003e\");\n  });\n\n  app.listen(PORT, () =\u003e {\n    console.log(`server is running at http://localhost:${PORT}`);\n  });\n  ```\n\n### [2.3 http methods and postman](https://youtu.be/AnCkn--EAas)\n\n- HTTP methods - get, post, put, patch, delete ...\n- get methods helps to get a resource or data\n- post method helps to create new resource\n- put method helps to update a resource\n- patch method helps to update single item of a resource\n- delete method helps to delete a resource\n- example\n\n  ```js\n  // index.js\n\n  const express = require(\"express\");\n\n  const PORT = 3000;\n\n  const app = express();\n\n  // http://localhost:3000/user\n\n  // this will work for all http methods: get, post so use app.get() or anything specific\n  app.use(\"/user\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to get request of express server \u003c/h1\u003e\");\n  });\n\n  app.get(\"/user\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to get request of express server \u003c/h1\u003e\");\n  });\n\n  app.post(\"/user\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to post request of express server \u003c/h1\u003e\");\n  });\n\n  // put is for updating multiple property\n  // patch is for updating one property\n\n  app.put(\"/user\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to put request of express server \u003c/h1\u003e\");\n  });\n\n  app.patch(\"/user\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to patch request of express server \u003c/h1\u003e\");\n  });\n\n  app.delete(\"/user\", (req, res) =\u003e {\n    res.send(\"\u003ch1\u003e Welcome to delete request of express server \u003c/h1\u003e\");\n  });\n\n  app.listen(PORT, () =\u003e {\n    console.log(`server is running at http://localhost:${PORT}`);\n  });\n\n  // error handling\n  app.use((req, res) =\u003e {\n    res.send(\"\u003ch2\u003ePage not found 404\u003c/h2\u003e\");\n  });\n\n  app.use((err, req, res, next) =\u003e {\n    console.error(err.stack);\n    res.status(500).send(\"Something broke!\");\n  });\n  ```\n\n### [2.4 Express Router](https://youtu.be/S7oFcdUiF1k)\n\n- use morgan package for getting more info about routing on console\n\n  ```js\n     step1 : npm install morgan\n     step2 : const morgan = require(\"morgan\");\n     step3 : app.use(morgan(\"dev\"));\n  ```\n\n- example\n\n  ```js\n  // step1: creates a routes folder\n  // setp2: create a file name as user.routes.js\n  // step3: write the following code inside user.routes.js\n  const express = require(\"express\");\n\n  const router = express.Router();\n\n  // /users\n  router.get(\"/\", (req, res) =\u003e {\n    res.send(\"I am get method of user route\");\n  });\n\n  router.post(\"/\", (req, res) =\u003e {\n    res.send(\"I am post method of user route\");\n  });\n\n  router.put(\"/\", (req, res) =\u003e {\n    res.send(\"I am put method of user route\");\n  });\n\n  router.patch(\"/\", (req, res) =\u003e {\n    res.send(\"I am patch method of user route\");\n  });\n\n  router.delete(\"/\", (req, res) =\u003e {\n    res.send(\"I am delete method of user route\");\n  });\n\n  module.exports = router;\n\n  //step4: write following code inside index.js\n  const express = require(\"express\");\n\n  const userRoutes = require(\"./routes/user.routes\");\n\n  const PORT = 3000;\n\n  const app = express();\n\n  app.use(\"/users\", userRoutes);\n\n  app.listen(PORT, () =\u003e {\n    console.log(`server is running at http://localhost:${PORT}`);\n  });\n  ```\n\n- example 2\n\n  ```js\n  const express = require(\"express\");\n  const router = express.Router();\n\n  // how to get the path\n  const path = require(\"path\");\n\n  const getFileLocation = (fileName) =\u003e {\n    return path.join(__dirname, `../views/${fileName}`);\n  };\n\n  router.get(\"/\", (req, res) =\u003e {\n    res.sendFile(getFileLocation(\"index.html\"));\n  });\n  router.get(\"/register\", (req, res) =\u003e {\n    res.sendFile(getFileLocation(\"register.html\"));\n  });\n  router.get(\"/login\", (req, res) =\u003e {\n    res.sendFile(getFileLocation(\"login.html\"));\n  });\n  module.exports = router;\n  ```\n\n### [2.5 regular expression \u0026 wild card Router]()\n\n```js\n//regular expression\n// we can use 0-9 but maximum 4 digits combination\nrouter.get(\"/search/:id([0-9]{4})\", (req, res) =\u003e {\n  res.status(200).send(\"serach user by id\" + req.params.id);\n});\n\n// only letters allowed with maximum 5 characters\nrouter.get(\"/search-username/:name([a-zA-Z]{5})\", (req, res) =\u003e {\n  res.status(200).send(\"serach user by name\" + req.params.name);\n});\n\n// wild cart\nrouter.get(\"*\", (req, res) =\u003e {\n  res.status(404).send({\n    message: \"url not found\",\n  });\n});\n```\n\n### [2.6 Express generator]()\n\n- package `npx espress-generator`\n- create a basic standard scalable folder structure with necessary codes\n\n### [2.7 HTTP Response](https://youtu.be/S7oFcdUiF1k)\n\n- response can be text, html, json\n- res.send(\"some text here\");\n- res.status(statuscode).json({...});\n- res.sendFile(fileName);\n- res.cookie(key, value);\n- res.clrarCookie(key);\n- res.writeHead()\n- res.write()\n- res.end()\n- res.append(key, value); this will set as response header\n\n![status-code](images/status-code.jpg)\n\n### [2.8 HTTP Request part-1](https://youtu.be/141Q7XhGGS8)\n\n- request with query parameter - req.query.parameterName\n- request with route parameters - req.params.parameterName\n- request with headers - req.header(key)\n- request with json data / form data inside body - req.body.parameterName\n- query parameter has question mark; search something on google.\n\n  - example of query parameter - http://localhost:3000?id=101\u0026name=anisul islam\n\n    - we can get the value using req.query.id and req.query.name\n\n    ```js\n    router.post(\"/\", (req, res) =\u003e {\n      console.log(req.query);\n      console.log(req.query.id);\n      console.log(req.query.name);\n      res.send(\"I am get method of user route\");\n    });\n    ```\n\n### [2.9 HTTP Request part-2](https://youtu.be/141Q7XhGGS8)\n\n- example of routes parameter\n\n  - http://localhost:3000/101\n  - we can get the value using req.params.id\n\n    ```js\n    router.post(\"/:id\", (req, res) =\u003e {\n      console.log(req.params.id);\n      res.send(\"I am get method of user route\");\n    });\n    ```\n\n- example of how to get data header requests\n\n  ```js\n  router.post(\"/\", (req, res) =\u003e {\n    console.log(req.header(\"id\"));\n    res.send(\"I am get method of user route\");\n  });\n  ```\n\n### [2.10 HTTP Request part-3](https://youtu.be/141Q7XhGGS8)\n\n- example of request with json data\n\n  - first add `app.use(express.json())`; for form data use `app.use(express.urlencoded({extended: true}))`\n  - then access the data using `req.body.parameterName`\n\n  ```js\n  // sending json or from data when making request\n  {\n    \"name\" : \"anisul\"\n  }\n\n  router.post(\"/\", (req, res) =\u003e {\n    res.status(201).json({\n      message: \"user is created\",\n      name: req.body.name,\n    });\n  });\n  ```\n\n### [2.11 send and receive from data](https://youtu.be/GXkth_xoG64)\n\n- create a index.html file inside views folder\n\n  ```html\n  \u003c!DOCTYPE html\u003e\n  \u003chtml lang=\"en\"\u003e\n    \u003chead\u003e\n      \u003cmeta charset=\"UTF-8\" /\u003e\n      \u003ctitle\u003ehome\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n      \u003cnav\u003e\n        \u003cul\u003e\n          \u003cli\u003e\u003ca href=\"/\"\u003eHome\u003c/a\u003e\u003c/li\u003e\n        \u003c/ul\u003e\n      \u003c/nav\u003e\n      \u003cmain\u003e\n        \u003ch1\u003ewelcome to home page\u003c/h1\u003e\n        \u003cform action=\"/users\" method=\"post\"\u003e\n          \u003clabel for=\"name\"\u003eName\u003c/label\u003e\n          \u003cinput type=\"text\" id=\"name\" name=\"name\" /\u003e\n          \u003cbutton type=\"submit\"\u003eRegister\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/main\u003e\n    \u003c/body\u003e\n  \u003c/html\u003e\n  ```\n\n- load a html file\n\n  ```js\n  // Inside user.routes.js file\n  const express = require(\"express\");\n  const path = require(\"path\");\n\n  const router = express.Router();\n\n  router.get(\"/\", (req, res) =\u003e {\n    res.sendFile(path.join(__dirname, \"../views/index.html\"));\n  });\n\n  router.post(\"/\", (req, res) =\u003e {\n    res.status(201).json({\n      message: \"user is created\",\n      name: req.body.name,\n    });\n  });\n\n  module.exports = router;\n\n  // inside index.js\n  const express = require(\"express\");\n\n  const userRoutes = require(\"./routes/user.routes\");\n\n  const PORT = 3000;\n\n  const app = express();\n\n  app.use(express.json());\n  app.use(express.urlencoded({ extended: true }));\n  app.use(\"/users\", userRoutes);\n\n  app.listen(PORT, () =\u003e {\n    console.log(`server is running at http://localhost:${PORT}`);\n  });\n  ```\n\n### [2.12 Area Calculator](https://youtu.be/u1BgJg6YzYM)\n\n### [2.13 How to set .env variables](https://youtu.be/dxwUjw2Jyfc)\n\n- Step 1: create an .env file in the root directory\n\n- Step 2: define environment variable(S) using uppercase letters and underscore if more than one word. Example -\n  PORT\n  DATABASE_URL\n\n- Step 3: Assign the values without double quotation and space\n  PORT=3000\n  DATABASE_URL=mongodb+srv://medo:demo1234@cluster0.0tl3q.mongodb.net/test?retryWrites=true\u0026w=majority\n\n- Step 4: you can make a comment using #\n\n  ```js\n  # server port\n  PORT=3000\n  ```\n\n- Step 5: install dotenv package - npm install dotenv\n\n- Step 6: require dotenv - require('dotenv').config();\n\n- Step 7: Access the env variables from anywhere using process.env.VARIABLE_NAME. Example – process.env.PORT;\n\n- Optional: DotENV Extension - nice syntax highlighting in your .env files.\n\n### [2.14 Middlewares](https://youtu.be/byiRZfg2JaE)\n\n- what is middleware?\n  - middleware is a function; it contains request obejct, response object and next function\n- why middleware?\n  - execute any code inside middleware\n  - we can make changes to the request and response object\n  - we can end the request and response cycle.\n  - we can call the next middleware in the stack.\n- some common usage of middleware\n\n  - user is authenticated or not\n  - check user is active or not\n  - data is correct / all data available\n\n- Types of middleware\n\n  - Application Level middleware: app.use(), app.METHOD(); here METHOD can be get, put, post, delete, patch\n  - router Level middleware: router.use(),router.METHOD()\n  - built-in Level middleware: express.json(), express.urlencoded(), express.static()\n  - third-party Level middleware: body-parser\n  - error handling middleware\n\n    ```js\n    // routes not found error\n    app.use((req, res, next) =\u003e {\n      res.status(404).json({\n        message: \"resource not found\",\n      });\n    });\n\n    // server error\n    app.use((err, req, res, next) =\u003e {\n      console.log(err);\n      res.status(500).json({\n        message: \"something broke\",\n      });\n    });\n    ```\n\n### [2.15 express static Middlewares](https://youtu.be/lqRIy6d6D48)\n\n- `app.use(express.static());` helps us to use static resources such as css and image inside our server\n\n### [2.16 MVC Architecture](https://youtu.be/BDeBB9b2L9I)\n\n- MVC Architecture means Model View Controller Architecture\n- Model holds all the database related codes\n- View is what users see\n- Controller is the connection point between Model and View. basically It deals with all the logic.\n- example of mvc file structure: setup a project and install necessary packages ( npm init -y \u0026\u0026 npm install nodemon express body-parser cors)\n\n  \u003cimg width=\"203\" alt=\"Screenshot 2022-04-26 at 05 13 08\" src=\"https://user-images.githubusercontent.com/28184926/165205917-0b83ecc1-9145-40ac-b92f-b8e8cb7511b4.png\"\u003e\n\n- controllers - user.controller.js\n\n  ```js\n  const path = require(\"path\");\n  const users = require(\"../models/user.model\");\n\n  const getUser = (req, res) =\u003e {\n    res.status(200).json({\n      users,\n    });\n  };\n\n  const createUser = (req, res) =\u003e {\n    const user = {\n      username: req.body.username,\n      email: req.body.email,\n    };\n    users.push(user);\n    res.status(201).json(users);\n  };\n\n  module.exports = { getUser, createUser };\n  ```\n\n- models\n\n  - user.model.js\n\n    ```js\n    const users = [\n      {\n        username: \"anisul islam\",\n        email: \"lalalal@yahoo.com\",\n      },\n      {\n        username: \"rakibul islam\",\n        email: \"lalalal@yahoo.com\",\n      },\n    ];\n    module.exports = users;\n    ```\n\n- routes\n\n  - user.route.js\n\n    ```js\n    const express = require(\"express\");\n    const { getUser, createUser } = require(\"../controllers/user.controller\");\n    const router = express.Router();\n\n    router.get(\"/\", getUser);\n    router.post(\"/\", createUser);\n\n    module.exports = router;\n    ```\n\n- views\n\n  - index.html\n\n    ```html\n    \u003c!DOCTYPE html\u003e\n    \u003chtml lang=\"en\"\u003e\n      \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003cnav\u003e\n          \u003cul\u003e\n            \u003cli\u003e\u003ca href=\"/\"\u003eHome\u003c/a\u003e\u003c/li\u003e\n            \u003cli\u003e\u003ca href=\"/api/users\"\u003eRegister\u003c/a\u003e\u003c/li\u003e\n          \u003c/ul\u003e\n        \u003c/nav\u003e\n        \u003ch1\u003eHome Page\u003c/h1\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n    ```\n\n    - user.html\n\n    ```html\n    \u003c!DOCTYPE html\u003e\n    \u003chtml lang=\"en\"\u003e\n      \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n        \u003cmeta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /\u003e\n        \u003cmeta name=\"viewport\" content=\"width=], initial-scale=1.0\" /\u003e\n        \u003ctitle\u003eDocument\u003c/title\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003cnav\u003e\n          \u003cul\u003e\n            \u003cli\u003e\u003ca href=\"/\"\u003eHome\u003c/a\u003e\u003c/li\u003e\n            \u003cli\u003e\u003ca href=\"/api/users\"\u003eRegister\u003c/a\u003e\u003c/li\u003e\n          \u003c/ul\u003e\n        \u003c/nav\u003e\n        \u003ch1\u003eUser Registration\u003c/h1\u003e\n        \u003cform action=\"/api/user\" method=\"post\"\u003e\n          \u003cinput type=\"text\" name=\"username\" placeholder=\"username\" /\u003e\n          \u003cinput type=\"email\" name=\"email\" placeholder=\"email\" /\u003e\n          \u003cbutton type=\"submit\"\u003eregister\u003c/button\u003e\n        \u003c/form\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n    ```\n\n- .env\n  - `PORT=4000`\n- app.js\n\n  ```js\n  const express = require(\"express\");\n  const cors = require(\"cors\");\n  const app = express();\n  const bodyParser = require(\"body-parser\");\n  const userRouter = require(\"./routes/user.route\");\n  // CORS\n  app.use(bodyParser.urlencoded({ extended: true }));\n  app.use(bodyParser.json());\n  app.use(cors());\n\n  app.use(\"/api/users\", userRouter);\n\n  app.get(\"/\", (req, res) =\u003e {\n    res.sendFile(__dirname + \"/views/index.html\");\n  });\n\n  // routes not found error\n  app.use((req, res, next) =\u003e {\n    res.status(404).json({\n      message: \"resource not found\",\n    });\n  });\n\n  // server error\n  app.use((err, req, res, next) =\u003e {\n    console.log(err);\n    res.status(500).json({\n      message: \"something broke\",\n    });\n  });\n\n  module.exports = app;\n  ```\n\n- index.js\n\n  ```js\n  require(\"dotenv\").config();\n  const app = require(\"./app\");\n  const PORT = process.env.PORT || 5000;\n  app.listen(PORT, () =\u003e {\n    console.log(`server is running at http://localhost:${PORT}`);\n  });\n  ```\n\n### [2.17] Validation with express-validator\n\n- install express-validator\n\n## Version-2 Express server with a project\n\n## Express tutorial\n\n## 1. Create an express server\n\n- initialize npm and install packages\n- nodemon montior the changes of our code and update the server\n\n```js\nnpm init -y \u0026\u0026 npm install express\nnpm install -D nodemon\n```\n\n```js\n// index.js\nconst express = require(\"express\");\n\nconst app = express();\n\nconst port = 3001;\n\napp.listen(port, () =\u003e {\n  console.log(`server is running at http://localhost:${port}`);\n});\n```\n\n```json\n//package.json\n\"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n    \"start\": \"node src/index.js\",\n    \"start-dev\": \"nodemon src/index.js\"\n  },\n```\n\n## 2. setting environment variables\n\n## 3. Handle GET Request -\u003e GET all products\n\n- routing plan using HTTP methods for RESTful Services\n- HTTP Verbs -\u003e GET, POST, PUT, PATCH, DELETE helps us to CRUD operations\n\n```js\nGET /products - get all the products -\u003e 200 (ok) / 404 (not found)\nGET /products/:id - get a single product -\u003e 200 / 404\nPOST /products/ - create a single product -\u003e 201 (Created) / 404 (Not Found) / 409 (Conflict -\u003e Already Exist)\nPUT /products/:id - update/replace every resource in a single product -\u003e 200 (Ok) / 404 (Not Found) / 405 (Method Not Allowed)\nPATCH /products/:id - update/Modify product itself -\u003e 200 (Ok) / 404 (Not Found)  / 405 (Method Not Allowed)\nDELETE /products/:id - delete a single product -\u003e 200 (Ok) / 404 (Not Found) / 405 (Method Not Allowed)\n\n```\n\n```js\n// app.use()\napp.use(\"/\", (req, res) =\u003e {\n  res.send(\"home page\");\n});\n\n// now use ThunderClient extension for testing the API; you will see app.use() accept all http methods\n\n// app.get() - will only accept get method\napp.get(\"/\", (req, res) =\u003e {\n  res.send(\"home page\");\n});\n```\n\n```js\nlet products = [\n  {\n    id: 1,\n    title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n    price: 109.95,\n  },\n  {\n    id: 2,\n    title: \"Mens Casual Premium Slim Fit T-Shirts \",\n    price: 22.3,\n  },\n];\n\napp.get(\"/products\", (req, res) =\u003e {\n  res.send(products);\n});\n```\n\n## 4. Middleware\n\n## 5. Handling error\n\n```js\n// client error\napp.use((req, res) =\u003e {\n  res.send(\"\u003ch2\u003ePage not found 404\u003c/h2\u003e\");\n});\n\n// server error\napp.use((err, req, res, next) =\u003e {\n  console.error(err.stack);\n  res.send(\"Something broke!\");\n});\n```\n\n## 6. Response Object\n\n- text, HTML, JSON\n\n```js\nres.send(\"hello\");\nres.send({\n  success: true,\n  user: { id: 1, name: \"anisul\" },\n});\nres.sendFile(\"hello.html\");\n```\n\n## 7. [Status codes](https://devhints.io/http-status)\n\n```js\napp.get(\"/\", (req, res) =\u003e {\n  res.status(200).send(\"home page\");\n});\n\napp.get(\"/products\", (req, res) =\u003e {\n  res.status(200).send(products);\n});\n\napp.use((req, res) =\u003e {\n  res.status(404).send(\"\u003ch2\u003ePage not found 404\u003c/h2\u003e\");\n});\n\napp.use((err, req, res, next) =\u003e {\n  console.error(err.stack);\n  res.status(500).send(\"Something broke!\");\n});\n```\n\n## 8. Request Object\n\n- request with query parameter - req.query.parameterName\n\n- request with route parameters - req.params.parameterName\n\n- request with headers - req.header(key)\n\n- request with json data / form data inside body - req.body.parameterName\n\n- query parameter has question mark; search something on google.\n\n- example of query parameter - http://localhost:3000?id=101\u0026name=anisul islam\n\n- we can get the value using req.query.id and req.query.name\n\n```js\nrouter.post(\"/\", (req, res) =\u003e {\n  console.log(req.query);\n  console.log(req.query.id);\n  console.log(req.query.name);\n  res.send(\"I am get method of user route\");\n});\n```\n\n## 9. Handle GET Request -\u003e get a single product\n\n```js\n// route parameter\napp.get(\"/products/:id\", (req, res) =\u003e {\n  const singleProduct = products.find(\n    (product) =\u003e product.id === Number(req.params.id)\n  );\n  res.status(200).send(singleProduct);\n});\n\n// query parameter\nconst sortItems = (sortBy, items) =\u003e {\n  if (sortBy === \"ASC\") {\n    return items.sort((a, b) =\u003e a.price - b.price);\n  } else if (sortBy === \"DESC\") {\n    return items.sort((a, b) =\u003e b.price - a.price);\n  }\n};\n\nconst sortItems = (sortBy, items) =\u003e {\n  if (sortBy === \"ASC\") {\n    return items.sort((a, b) =\u003e a.price - b.price);\n  } else if (sortBy === \"DESC\") {\n    return items.sort((a, b) =\u003e b.price - a.price);\n  }\n};\n\napp.get(\"/products\", (req, res) =\u003e {\n  const maxPrice = Number(req.query.maxPrice);\n  const sortBy = req.query.sortBy;\n  let result;\n  if (maxPrice) {\n    result = products.filter((product) =\u003e product.price \u003c= maxPrice);\n    result = sortBy ? sortItems(sortBy, result) : result;\n    res.status(200).send(result);\n  } else {\n    res.status(200).send(products);\n  }\n});\n```\n\n## 10. Handle POST Request -\u003e create a single product\n\n```js\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\napp.post(\"/products\", (req, res) =\u003e {\n  const newProduct = {\n    id: Number(req.body.id),\n    title: req.body.title,\n    price: req.body.price,\n  };\n  products.push(newProduct);\n  res.status(200).send(newProduct);\n});\n```\n\n## 11. Handle DELETE Request -\u003e delete a single product\n\n```js\napp.delete(\"/products/:id\", (req, res) =\u003e {\n  products = products.filter((product) =\u003e product.id !== Number(req.params.id));\n  res.status(200).send(products);\n});\n```\n\n## 12. Handle PUT Request -\u003e update a single product\n\n```js\napp.put(\"/products/:id\", (req, res) =\u003e {\n  products\n    .filter((product) =\u003e product.id === Number(req.params.id))\n    .map((product) =\u003e {\n      product.title = req.body.title;\n      product.price = req.body.price;\n    });\n  res.status(200).send(products);\n});\n```\n\n## 13. MVC Structure - Routing with express Router\n\n- Separation of Concerns\n- Model, View, Controllers\n- create a router folder and then create a product file where we will move all our routes\n\n```js\n//routes -\u003e product.js\nconst express = require(\"express\");\nconst router = express.Router();\n\nlet products = [\n  {\n    id: 1,\n    title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n    price: 109.95,\n  },\n  {\n    id: 2,\n    title: \"Mens Casual Premium Slim Fit T-Shirts \",\n    price: 22.3,\n  },\n  {\n    id: 3,\n    title: \"Mens Cotton Jacket\",\n    price: 55.99,\n  },\n  { id: 4, title: \"Mens Casual Slim Fit\", price: 15.99 },\n];\n\nconst sortItems = (sortBy, items) =\u003e {\n  if (sortBy === \"ASC\") {\n    return items.sort((a, b) =\u003e a.price - b.price);\n  } else if (sortBy === \"DESC\") {\n    return items.sort((a, b) =\u003e b.price - a.price);\n  }\n};\n\nrouter.get(\"/products\", (req, res) =\u003e {\n  const maxPrice = Number(req.query.maxPrice);\n  const sortBy = req.query.sortBy;\n  let result;\n  if (maxPrice) {\n    result = products.filter((product) =\u003e product.price \u003c= maxPrice);\n    result = sortBy ? sortItems(sortBy, result) : result;\n    res.status(200).send(result);\n  } else {\n    res.status(200).send(products);\n  }\n});\n\nrouter.get(\"/products/:id\", (req, res) =\u003e {\n  const singleProduct = products.find(\n    (product) =\u003e product.id === Number(req.params.id)\n  );\n  res.status(200).send(singleProduct);\n});\n\nrouter.post(\"/products\", (req, res) =\u003e {\n  const newProduct = {\n    id: Number(req.body.id),\n    title: req.body.title,\n    price: req.body.price,\n  };\n  products.push(newProduct);\n  res.status(200).send(newProduct);\n});\n\nrouter.put(\"/products/:id\", (req, res) =\u003e {\n  products\n    .filter((product) =\u003e product.id === Number(req.params.id))\n    .map((product) =\u003e {\n      product.title = req.body.title;\n      product.price = req.body.price;\n    });\n  res.status(200).send(products);\n});\n\nrouter.delete(\"/products/:id\", (req, res) =\u003e {\n  products = products.filter((product) =\u003e product.id !== Number(req.params.id));\n  res.status(200).send(products);\n});\n\nmodule.exports = router;\n\n// inside index.js\nconst productRouters = require(\"./router/products\");\napp.use(productRouters);\n```\n\n- remove all the products and in index.js use `app.use(\"/products\", productRouters);`\n\n## 14. MVC Structure - Controller part\n\n```js\n// routes -\u003e products.js\nconst express = require(\"express\");\nconst {\n  getAllProducts,\n  getSingleProduct,\n  createProduct,\n  updateProduct,\n  deleteProduct,\n} = require(\"../controller/products\");\nconst router = express.Router();\n\nrouter.get(\"/\", getAllProducts).get(\"/:id\", getSingleProduct);\n\nrouter.post(\"/\", createProduct);\n\nrouter.put(\"/:id\", updateProduct);\n\nrouter.delete(\"/:id\", deleteProduct);\n\nmodule.exports = router;\n\n// controller -\u003e products.js\nlet products = [\n  {\n    id: 1,\n    title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n    price: 109.95,\n  },\n  {\n    id: 2,\n    title: \"Mens Casual Premium Slim Fit T-Shirts \",\n    price: 22.3,\n  },\n  {\n    id: 3,\n    title: \"Mens Cotton Jacket\",\n    price: 55.99,\n  },\n  { id: 4, title: \"Mens Casual Slim Fit\", price: 15.99 },\n];\n\nconst sortItems = (sortBy, items) =\u003e {\n  if (sortBy === \"ASC\") {\n    return items.sort((a, b) =\u003e a.price - b.price);\n  } else if (sortBy === \"DESC\") {\n    return items.sort((a, b) =\u003e b.price - a.price);\n  }\n};\n\nconst getAllProducts = (req, res) =\u003e {\n  const maxPrice = Number(req.query.maxPrice);\n  const sortBy = req.query.sortBy;\n  let result;\n  if (maxPrice) {\n    result = products.filter((product) =\u003e product.price \u003c= maxPrice);\n    result = sortBy ? sortItems(sortBy, result) : result;\n    res.status(200).send(result);\n  } else {\n    res.status(200).send(products);\n  }\n};\n\nconst getSingleProduct = (req, res) =\u003e {\n  const singleProduct = products.find(\n    (product) =\u003e product.id === Number(req.params.id)\n  );\n  res.status(200).send(singleProduct);\n};\n\nconst createProduct = (req, res) =\u003e {\n  const newProduct = {\n    id: Number(req.body.id),\n    title: req.body.title,\n    price: req.body.price,\n  };\n  products.push(newProduct);\n  res.status(200).send(newProduct);\n};\n\nconst updateProduct = (req, res) =\u003e {\n  products\n    .filter((product) =\u003e product.id === Number(req.params.id))\n    .map((product) =\u003e {\n      product.title = req.body.title;\n      product.price = req.body.price;\n    });\n  res.status(200).send(products);\n};\n\nconst deleteProduct = (req, res) =\u003e {\n  products = products.filter((product) =\u003e product.id !== Number(req.params.id));\n  res.status(200).send(products);\n};\n\nmodule.exports = {\n  getAllProducts,\n  getSingleProduct,\n  createProduct,\n  updateProduct,\n  deleteProduct,\n};\n```\n\n## 15. MVC Structure - Model part\n\n```js\n// model -\u003e products.js\nlet products = [\n  {\n    id: 1,\n    title: \"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops\",\n    price: 109.95,\n  },\n  {\n    id: 2,\n    title: \"Mens Casual Premium Slim Fit T-Shirts \",\n    price: 22.3,\n  },\n  {\n    id: 3,\n    title: \"Mens Cotton Jacket\",\n    price: 55.99,\n  },\n  { id: 4, title: \"Mens Casual Slim Fit\", price: 15.99 },\n];\n\nmodule.exports = products;\n```\n\n## 15. EJS\n\n## 16. Deploy on Heroku\n\n- `const port = process.env.PORT || 3001;`\n- Procfile -\u003e `web: node index.js`\n- add .gitignore file -\u003e `node_modules_`\n\n## 17. Database\n\n- save(), find(), findOne(), deleteOne(), updateOne()\n\n```js\nconst mongoose = require(\"mongoose\");\nmongoose\n  .connect(\"mongodb://localhost:27017/testProduct\")\n  .then(() =\u003e console.log(\"DB is connected\"))\n  .catch((error) =\u003e {\n    console.log(error.message);\n    process.exit(1);\n  });\n\n// schema \u0026 model\nconst { model } = require(\"mongoose\");\nconst mongoose = require(\"mongoose\");\n\nconst productsSchema = new mongoose.Schema({\n  id: Number,\n  title: String,\n  price: Number,\n});\n\nmodule.exports = model(\"Product\", productsSchema);\n\n// controller\nconst Products = require(\"../model/products\");\n\n// Create\nconst createProduct = async (req, res) =\u003e {\n  try {\n    const newProduct = new Products({\n      id: Number(req.body.id),\n      title: req.body.title,\n      price: req.body.price,\n    });\n    await newProduct.save();\n    res.status(200).send(newProduct);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n};\n\n// Read\nconst getAllProducts = async (req, res) =\u003e {\n  try {\n    const products = await Products.find();\n    res.status(200).send(products);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n};\n\n// read all the products\nconst getAllProducts = async (req, res) =\u003e {\n  try {\n    const products = await Products.find();\n    const maxPrice = Number(req.query.maxPrice);\n    const sortBy = req.query.sortBy;\n    let result;\n    if (maxPrice) {\n      result = await Products.find({ price: { $lt: maxPrice } });\n      result = sortBy ? sortItems(sortBy, result) : result;\n      res.status(200).send(result);\n    } else {\n      res.status(200).send(products);\n    }\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n};\n\n// read single product by id\nconst getSingleProduct = async (req, res) =\u003e {\n  try {\n    // const id = parseInt(req.params.id);\n    const singleProduct = await Products.findOne({ req.params.id });\n    res.status(200).send(singleProduct);\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n};\n\n// delete one product by id\nconst deleteProduct = async (req, res) =\u003e {\n  try {\n    const id = parseInt(req.params.id);\n    const singleProduct = await Products.deleteOne({ id });\n    res.status(200).send({ success: true });\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n};\n\n// update a product by id\nconst updateProduct = async (req, res) =\u003e {\n  try {\n    await Products.updateOne(\n      { id: req.params.id },\n      {\n        $set: {\n          title: req.body.title,\n          price: req.body.price,\n        },\n      }\n    );\n    res.status(200).send({ success: true });\n  } catch (error) {\n    res.status(500).send(error.message);\n  }\n};\n```\n\n## 18. cors setup\n\n- cors setup\n\n```js\nnpm install cors\napp.use(cors())\n```\n\n## 19. connection from front end\n\n```js\nimport \"./App.css\";\nimport React, { useEffect, useState } from \"react\";\nimport NewProduct from \"./components/NewProduct\";\n\nconst URL = \"http://localhost:4000/products\";\nfunction App() {\n  const [products, setProducts] = useState([]);\n  const [isLoading, setIsLoading] = useState(true);\n  const [error, setError] = useState(null);\n\n  // update\n  const [selectedProduct, setSelectedProduct] = useState({\n    title: \"\",\n    price: \"\",\n  });\n  const [updateFlag, setUpdateFlag] = useState(false);\n  const [selectedProductId, setSelectedProductId] = useState(\"\");\n\n  const getAllProducts = () =\u003e {\n    fetch(URL)\n      .then((res) =\u003e {\n        if (!res.ok) {\n          throw Error(\"could not fetch\");\n        }\n        return res.json();\n      })\n      .then((result) =\u003e {\n        setProducts(result);\n      })\n      .catch((err) =\u003e {\n        setError(err.message);\n      })\n      .finally(() =\u003e {\n        setIsLoading(false);\n      });\n  };\n  useEffect(() =\u003e {\n    getAllProducts();\n  }, []);\n\n  const handleDelete = (id) =\u003e {\n    fetch(URL + `${id}`, {\n      method: \"DELETE\",\n    })\n      .then((res) =\u003e {\n        if (!res.ok) {\n          throw Error(\"could not delete\");\n        }\n        getAllProducts();\n      })\n      .catch((err) =\u003e {\n        setError(err.message);\n      });\n  };\n\n  const addProduct = (product) =\u003e {\n    fetch(URL, {\n      method: \"POST\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify(product),\n    })\n      .then((res) =\u003e {\n        if (res.status === 201) {\n          getAllProducts();\n        } else {\n          throw new Error(\"could not create new product\");\n        }\n      })\n      .catch((err) =\u003e {\n        setError(err.message);\n      });\n  };\n\n  const handleEdit = (id) =\u003e {\n    setSelectedProductId(id);\n    setUpdateFlag(true);\n    const filteredData = products.filter((product) =\u003e product.id === id);\n    setSelectedProduct({\n      title: filteredData[0].title,\n      price: filteredData[0].price,\n    });\n  };\n\n  const handleUpdate = (product) =\u003e {\n    console.log(selectedProductId);\n    fetch(URL + `/${selectedProductId}`, {\n      method: \"PUT\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n      body: JSON.stringify(product),\n    })\n      .then((res) =\u003e {\n        if (!res.ok) {\n          throw new Error(\"failed to update\");\n        }\n        getAllProducts();\n        setUpdateFlag(false);\n      })\n      .catch((err) =\u003e {\n        setError(err.message);\n      });\n  };\n\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003ch1\u003eProducts\u003c/h1\u003e\n      {isLoading \u0026\u0026 \u003ch2\u003eLoading...\u003c/h2\u003e}\n      {error \u0026\u0026 \u003ch2\u003e{error}\u003c/h2\u003e}\n\n      {updateFlag ? (\n        \u003cNewProduct\n          btnText=\"Update Product\"\n          selectedProduct={selectedProduct}\n          handleSubmitData={handleUpdate}\n        /\u003e\n      ) : (\n        \u003cNewProduct btnText=\"Add Product\" handleSubmitData={addProduct} /\u003e\n      )}\n\n      {products.length \u003e 0 \u0026\u0026\n        products.map((product) =\u003e (\n          \u003carticle key={product.id}\u003e\n            \u003ch3\u003e{product.title}\u003c/h3\u003e\n            \u003cp\u003e{product.price}\u003c/p\u003e\n            \u003cbutton\n              onClick={() =\u003e {\n                handleEdit(product.id);\n              }}\n            \u003e\n              Edit\n            \u003c/button\u003e\n            \u003cbutton\n              onClick={() =\u003e {\n                handleDelete(product.id);\n              }}\n            \u003e\n              Delete\n            \u003c/button\u003e\n          \u003c/article\u003e\n        ))}\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n\n\n// NewProduct.js\nimport React, { useState, useEffect } from \"react\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nconst NewProduct = ({ handleSubmitData, selectedProduct, btnText }) =\u003e {\n  const [product, setProduct] = useState({\n    title: \"\",\n    price: \"\",\n  });\n\n  const { title, price } = product;\n\n  useEffect(() =\u003e {\n    setProduct({\n      title: selectedProduct.title,\n      price: selectedProduct.price,\n    });\n  }, [selectedProduct]);\n\n  const handleChange = (e) =\u003e {\n    const selectedField = e.target.name;\n    const selectedValue = e.target.value;\n    setProduct((prevState) =\u003e {\n      return { ...prevState, [selectedField]: selectedValue };\n    });\n  };\n\n  const handleSubmit = (e) =\u003e {\n    e.preventDefault();\n    const newProduct = {\n      id: Number(uuidv4()),\n      title: product.title,\n      price: product.price,\n    };\n    handleSubmitData(newProduct);\n    setProduct({\n      title: \"\",\n      price: \"\",\n    });\n  };\n\n  return (\n    \u003cform onSubmit={handleSubmit}\u003e\n      \u003cdiv className=\"field-group\"\u003e\n        \u003clabel htmlFor=\"title\"\u003eTitle: \u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          id=\"title\"\n          name=\"title\"\n          value={title}\n          onChange={handleChange}\n          required\n        /\u003e\n      \u003c/div\u003e\n      \u003cdiv className=\"field-group\"\u003e\n        \u003clabel htmlFor=\"price\"\u003ePrice: \u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          id=\"price\"\n          name=\"price\"\n          value={price}\n          onChange={handleChange}\n          required\n        /\u003e\n      \u003c/div\u003e\n      \u003cbutton type=\"submit\" className=\"btn\"\u003e\n        {btnText}\n      \u003c/button\u003e\n    \u003c/form\u003e\n  );\n};\n\nNewProduct.defaultProps = {\n  selectedProduct: {\n    title: \"\",\n    price: \"\",\n  },\n};\n\nexport default NewProduct;\n\n```\n\n## CORS Setup\n\n## REST API\n\n- basically we are going to return some data\n- Reperesentational State Transfer\n- Response data -\u003e text, html, xml, json\n- HTTP methods -\u003e GET, POST, PUT (CREATE/OVERRIDE A RESOURCE) /PATCH, DELETE\n- Routing\n\n## Necessary Code\n\n```bash\nconst express = require(\"express\"); // Create Express server\nconst morgan = require(\"morgan\"); // For automatically run server\nconst cookieParser = require(\"cookie-parser\"); // For set Cookie\nconst createError = require(\"http-errors\"); // For create HTTP Error\nconst xssClean = require(\"xss-clean\"); // For  Secure API\nconst bodyParser = require(\"body-parser\"); // For Get/ Set data into body\nconst cors = require(\"cors\"); // To set access for client-side URL\n```\n\n/_\n|--------------------------------------------------------------------------\n| Initialize Middleware\n|--------------------------------------------------------------------------\n_/\n\n```bash\napp.use(cookieParser()); // For set Cookie\napp.use(morgan(\"dev\")); // For automatically run server\napp.use(xssClean()); // For  Secure api\napp.use(bodyParser.json()); // For Set, Read data into the body and display JSON Format Text\napp.use(bodyParser.urlencoded({ extended: true })); // Get HTML Form Data\napp.use(setRefreshToken); // For set Refresh Token [Automatically call this middleware for all route]\n// To get access to Client side URL\napp.use(cors(\n {\n   origin: BASE_URL, // Frontend Base URL\n   credentials: true\n }\n));\napp.use(express.static(\"public\")); // To Display Server site image\n```\n\n/_\n|--------------------------------------------------------------------------\n| Socket IO\n|--------------------------------------------------------------------------\n_/\n\n```bash\nconst io = require(\"socket.io\")(8080, {\n cors: {\n   origin: BASE_URL\n },\n});\nio.on(\"connection\", (socket) =\u003e {\n console.log(\"User connected\", socket.id);\n\n setInterval(() =\u003e {\n   io.emit(\"refresh\", {});\n }, 500)\n\n // socket.on(\"disconnect\", function () {\n //   console.log(\"Disconnect\");\n\n // })\n\n});\n```\n\n## Follow Me\n\n\u003cimg src =\"https://www.edigitalagency.com.au/wp-content/uploads/Facebook-logo-blue-circle-large-transparent-png.png\" height=\"15px\" width=\"15px\"/\u003e [Facebook](http://facebook.com/learnwithfair), \u003cimg src =\"https://image.similarpng.com/very-thumbnail/2021/10/Youtube-icon-design-on-transparent-background-PNG.png\" height=\"20px\" width=\"20px\"/\u003e [Youtube](http://youtube.com/@learnwithfair), \u003cimg src =\"https://i.pinimg.com/originals/fa/ea/02/faea02f412415becfb4939d2b6431c28.jpg\" height=\"15px\" width=\"15px\"/\u003e [Instagram](http://instagram.com/learnwithfair)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fnode-express-documentation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearnwithfair%2Fnode-express-documentation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearnwithfair%2Fnode-express-documentation/lists"}