Basics of API Development in Nodejs

  • mkdir mern-course
  • npm init
  • npm install -D nodemon

in package.json add script

"start": "nodemon app.js" npm install express

importing express

// converting this to es6 systax did not worked, don't know why
const express = require('express');
const app = express();

create server

  1. create server will accept port number and callback function will be called when server creation is successful.
app.listen(3000, ()=>{
    console.log("your server is started at http://localhost:3000")
})

creating get request,

app.get('/', (req, res) => {
    res.send('Helloo!!! API...')
})
Enviroment Variable

These variables are once created in .env file and can be used anywhere in application where needed.

  1. create .env file
API_URL = /api/v1
  1. npm install dotenv
  2. import dotenv library into application
require('dotenv/config')
const api = process.env.API_URL;
app.get(api+'/products', (req, res) => {
    res.send('Helloo!!! API...')
})

http://localhost:3000/api/v1/products

we will have two .env files on for production and one for development, in .env file we can store database strings, other keys etc

Get and Post method.

get method is used to send an object from database to front end. we create this object by retriving data from database.

app.get(`${api}+/products`, (req, res) => {
    const products = {
        id: 1,
        name: 'pen',
        color: 'white',
    }
    res.send(products);
})

post method is for receiving data from frontend and saving it somewhere. to parse/understand the data that is comming form user in JSON or whatever format we need some middlewhere to understand/parse data comming from user,

Using Body Parsing code in express app.use(express.json()); //Used to parse JSON bodies

app.use(express.urlencoded()); //Parse URL-encoded bodies

const express = require('express');
const app = express();
require('dotenv/config')

// Middleware section
app.use(express.json());




const api = process.env.API_URL;
app.get(`${api}/products`, (req, res) => {
    const products = {
        id: 1,
        name: 'pen',
        color: 'white',
    }
    res.send(products);
})


app.post(`${api}/products`, (req, res) => {
    const newProduct = req.body;
    console.log(newProduct);
    res.send(newProduct);
})


app.listen(3000, ()=>{
    console.log("your server is started at http://localhost:3000")
})

Logging

Logging http request npm install morgan

you require only two lines,

const morgan = require('morgan')
app.use(morgan('tiny'));
Creating Connection with database

npm install mongoose

visit https://cloud.mongodb.com/ -> Clusters -> Collection -> Create Database, enter the database name ex ‘eshop-database’ enter the collection name ex ‘eshop-collection’

in Security section click on Database Access -> Click on Add new database user

click on Clusters -> Connect -> Select option ‘Connect from anywhere’ -> in connection method select ‘connect to application’ -> copy the connection string and click close.

mongodb+srv://eshop-user:<password>@nodejs.xtcgi.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Add this connection string to variable in .env file.

CONNECTION_STRING = mongodb+srv://eshop-user:aSoxQgcGV9RJISzG@nodejs.xtcgi.mongodb.net/eshop-database?retryWrites=true&w=majority&authSource=admin

Errors

// Error Number 1
Error: connect ETIMEDOUT 3.7.243.141:27017
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
  name: 'MongoNetworkError'
}

// Solution of Error Number 1
//At the end of connection string add &authSource=admin like example below

`https://stackoverflow.com/questions/50173080/mongonetworkerror-failed-to-connect-to-server-localhost27017-on-first-connec`

`CONNECTION_STRING = mongodb+srv://eshop-user:aSoxQgcGV9RJISzG@nodejs.xtcgi.mongodb.net/eshop-database?retryWrites=true&w=majority&authSource=admin`
const mongoose = require('mongoose');

// mongoose connection string will be placed just before creating the server.
mongoose.connect(process.env.CONNECTION_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    dbName: 'eshop-database',
})
.then(()=>{
    console.log('Database Connection is Ready...')
})
.catch((err) => {
    console.log(err);
})

app.listen(3000, ()=>{
    console.log("your server is started at http://localhost:3000")
})
Next