Getting started with Express

beige and red train

Introduction

Installation

Step1:Create your node app

Give a name to your app and skip the rest of the values to get your first node project

npm init

Step2: Add some utilities

sudo npm install -g nodemon yarn

Step3: Create an express project using yarn package manager

yarn add express

Step4: Create your first server app

When you call hello from a browser, you will get a response

nodemon server.js

const express = require('express')
const app = express()
app.listen(4000, '0.0.0.0', () => {
  console.log(`express server started successfully`)
})
app.get('/hello', (request, response) => {
    response.send('Hello World')
})   

Connect to DB

Step1: Download Robo 3T and connect it to your DB

Step2: Add yarn add mongoDB, and create a js file to connect to DB

const express = require('express')
const MongoClient = require('mongodb').MongoClient
const app = express()

app.get('/emp', (request, response) => {
  // connect to the mongodb running on the local machine
  MongoClient.connect('mongodb://localhost:27017/classwork', (err, client) => {
    if (err) throw err
    const db = client.db('classwork')
    db.collection('emp')
      .find()
      .toArray((err, result) => {
        if (err) throw err
        response.send(result)
      })
  })
})

app.listen(4000, '0.0.0.0', () => {
  console.log('server started on port 4000')
})

Add Routes

Step1: Create your App using the above, with routes file(routes.js) added to routes folder

const express = require('express')
const router = express.Router()

router.post('/signup', (request, response) => {
    console.log(`name = ${request.body.name}`)
    console.log(`email = ${request.body.email}`)
    console.log(`password = ${request.body.password}`)
    response.send('user signed up')
  })

module.exports = router

Step2: Add route to the app server.js

const express = require('express')
const app = express()

app.use(express.json())

app.get('/', (request, response) => {
  response.send('<h1>Welcome to the Application Backend</h1>')
})
const routerUser = require('./routes/user')
app.use(routerUser)

app.listen(4000, '0.0.0.0', () => {
  console.log('server has started successfully on port 4000')
})

Step 3: Output from Postman

Create API with DB connectivity

SignUp with DB

Step1: Add Mongoose, and connect to DB

yarn add mongoose

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/tweeter')

Step2: Create user Model user.js inside models folder

const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
})
module.exports = mongoose.model('User', UserSchema)

Step3: Update SignUp endpoint

yarn add crypto-js for storing password Hash

const CryptoJs = require('crypto-js')
const utils = require('../utils')

router.post('/signup', (request, response) => {
    const { name, email, password } = request.body
  
    const user = new User()
    user.name = name
    user.email = email
    user.password = `${CryptoJs.SHA256(password)}`
  
    user.save((error, result) => {
      response.send(utils.createResult(error, result))
    })
  })

Add util helper for handling response

function createResult(error, data) {
    const result = {}
    if (error) {
    result['status'] = 'error'
      result['error'] = error
    } else {
      result['status'] = 'success'
      result['data'] = data
    }
    return result
  }
  
  module.exports = {
    createResult,
  }

Step4: Output for signup

SignIn with DB

Step1: Add the signing code

router.post('/signin', (request, response) => {
    const { email, password } = request.body
  
    User.findOne({ email: email, password: `${CryptoJs.SHA256(password)}` }).exec(
      (error, user) => {
        if (error) {
          response.send({ status: 'error', error: error })
        } else if (!user) {
          response.send({ status: 'error', error: 'invalid email or password' })
        } else {
          response.send({ status: 'success', data: 'successfully logged in' })
        }
      }
    )
  })

Output

JWT tokens

yarn add jsonwebtoken

Step1 : Add Config file

const config = {
    secret: 'b2VQXKIrB7urfisPxHuLss6Z2oTMR2MC',
  }
  
  module.exports = config

Step2 Add JSON web token when signed in

const jwt = require('jsonwebtoken')
const config = require('../config')

router.post('/signin', (request, response) => {
  const { email, password } = request.body

  User.findOne({ email: email, password: `${CryptoJs.SHA256(password)}` }).exec(
    (error, user) => {
      if (error) {
        response.send({ status: 'error', error: error })
      } else if (!user) {
        response.send({ status: 'error', error: 'invalid email or password' })
      } else {
        // create payload which will be sent to the client
        // and client will send it back every time while calling API
        const payload = {
          id: user._id,
        }

        // create jwt token
        const token = jwt.sign(payload, config.secret)

        // send the token to the user
        response.send({
          status: 'success',
          data: {
            email: user.email,
            name: user.name,
            token: token,
          },
        })
      }
    }
  )
})

Step3 : output

GitHub

https://github.com/jonesjalapatgithub/ExpressGettingStarted

Leave a Comment

Your email address will not be published.

error: Content is protected !!
Scroll to Top