- Create express.js web-server according to Express.js - SHORT GUIDE
-
Create simplest local proj db in """data/products.js""" & import
this db to server.js
-
data/products.js
See the Pen 2-local-db-file by Andrii (@imitator) on CodePen.
-
Next 2 points are for explanation, may be MISSED, so go
to point 7 of this guide
-
in our server.js file.
Import this db by
- const products = require('./data/products');
then make simplest root for giving that data by-
app.get('/products', (req, res) => {});
- res.json(products);
-
In html create script for getting data
-
<script>
-
const productsRequest = fetch(
'http://localhost:5555/products', );
productsRequest
-
.then(response => {
-
if (!response.ok) {
- throw new Error('Request error');
return response.json();})
.then(result => console.log(result)).catch(error => console.log(error)); -
if (!response.ok) {
-
.then(response => {
-
const productsRequest = fetch(
'http://localhost:5555/products', );
-
-
in our server.js file.
Import this db by
-
data/products.js
-
Create -- routes -- folder in our proj for separating routes
from main server.js
- Create file routes/products.routes.js for making routes for products endpoint
-
In routes/products.routes.js create list of products routes
by Router() from express
-
const express = require('express');
const router = express.Router();
-
const express = require('express');
-
Move importing data from server.js to
routes/products.routes.js
- const products = require('../data/products');
-
Move products route from server.js (if you made 6.101)
- app.get('/products', (req, res) => { res.json(products); });
- router.get('/', (req, res) => { res.json(products); });
See the Pen 3-routes/products.js by Andrii (@imitator) on CodePen.
-
In future we will have more routes, so we should group them
in some kind of
routes/index.js where we
reexport products
-
const products = require('./products.routes');module.exports = { products, };
-
-
Then import routes in
server.js
- const routes = require('./routes');
-
And use routes in server.js by middleware like
- app.use('/products', routes.products);
-
sometimes we should change api for new clients, but for old
clients we have to live old api, so write in server.js such
changes like
- app.use('/api/v1/products', routes.products);
For checking our products responding go to http://localhost:5555/api/v1/products
-
Create one more route with empty data
- routes/customers.routes.js
- Make reexports in routes/index.js according example above
-
server.js
- app.use('/api/v1/customers', routes.customers);
-
The next step in making convenient web-server is separating
functions/controllers from routes folder by creating
controllers folder in main project folder.
-
Create controllers/products folder, so move importing data &
controller from routes/products.js
-
controllers/products/getAll.js
const products = require('../../data/products'); const getAll = (req, res) => {res.json(products);}; module.exports = getAll;
-
controllers/products/getAll.js
-
Reexport functions from controllers folder by making
controller/products/index.js file
-
controller/products/index.js
const getAll = require('./getAll'); module.exports = {getAll };
-
controller/products/index.js
-
Import all products controllers from controllers/products
folder to controllers/index.js
-
controllers/index.js
const products = require('./products'); module.exports = { products };
-
controllers/index.js
-
Import products controllers from controller folder & use
necessary one
-
routes/products.routes.js
const express = require('express'); const router = express.Router(); const { products } = require('../controllers'); router.get('/', products.getAll); module.exports = router;
-
OR with renaming products to ctrl when importing
controllers
const express = require('express'); const router = express.Router(); const { products: ctrl } = require('../controllers'); router.get('/', ctrl.getAll); module.exports = router;
-
routes/products.routes.js
- More controllers do with Controllers making guide
-
Create controllers/products folder, so move importing data &
controller from routes/products.js
-
Push web-server from local computer to the server, f.e. heroku
or
free from the list
https://app.cyclic.sh/ example
- Go to https://app.cyclic.sh/
- Push the button "New App"
- Go from Starter Templates tab to Link Your Own
- Type the name of your repo in github & choose it, then press Connect button
- cyclic.sh link us to github service for asking of pushing Approve and install button.
- Add necessary variables, f.e. DB_HOST, SECRET_KEY etc.
-
Make connection to the real database on
MongoDB service.
- Press New Project button for creating one project for many databases
- Push the button Build a Database for creating first DB
- Choose nearest region & name a cluster
-
Go to Database Access tab for creating first user
- Name this user & create pass (f.e. login admin, password admintest)
- In Built-in Role point choose "Read and write to any database"
-
Go to Network Access tab
- Add IP Address
- For developing from anywhere, in example of many developers, choose/press Allow Access From Anywhere and push Confirm button
- Back to database tab and go to Cluster link
- Go to Collections tab & Load a Sample Dataset for learning or push "Add My Own Data" button
- Name database and collection (noun in plural)
-
To connect for database we should take a link,
- back to home page of Atlas (Mongo DB)
- Go to the necessary project
- Push the Connect button
- Choose Connect your application button, where copy link
- Change in link: user, password, database
- Database name must be between "mongodb.net/" and "?retryWrites", like ..mongodb.net/mydatabase?retryWrites..
- write this link to .env & name variable like DB_HOST
- In web-server install mongoose lib for working with mongoDb service npm i mongoose
-
Add mongoDB connection code
See the Pen 14 - MongoDB connection by Andrii (@imitator) on CodePen.
Also in good practice app should be started after we have connection to mongoDB, means like.then(() => {})console.log('DataBase was connected successfully');app.listen(PORT, console.log(`Server started on port ${PORT}`)),After "db is connected" refactor controllers according to work with mongoDb
-
Model & Schema for MongoDB theory, his point is used for
explanation
After successfully connection to database, we may try to add some object to our mongoDb db (only for explanation, b/c this object will be added every time in restarting application)
-
After "const mongoose = require('mongoose');"
declaration make the code
See the Pen 15 - Schema & model in web-server by Andrii (@imitator) on CodePen.
Schema name named in singular name of collection in some of codes we may see const productSchema = new Schema({}), but this is improved for shortest code
Model name in good practice named from big letter in singular noun, also first argument, in our case "product" named also as a name of collection, but in singular
-
After db was successfully connecter write the code
See the Pen 16 - example of object creating in MongoDB by Andrii (@imitator) on CodePen.
OR the same but for better practice if anything wrong.then(() => {console.log('DataBase was connected successfully');const newItem = {name: 'myBrand',};price: '5222',Product.create(newItem, (error, data) => {if (error) {console.log(error);}returnconsole.log(data);} );})OR the same, bt with Better practice of async functions
See the Pen 16 - A example of object creating in MongoDB with async by Andrii (@imitator) on CodePen.
-
After "const mongoose = require('mongoose');"
declaration make the code