DEV Community

Cover image for Express.js
UiX Phuke
UiX Phuke

Posted on

1

Express.js

What is Express?

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

initialisation:

npm init 
Enter fullscreen mode Exit fullscreen mode

installation of express:

npm install express --save 
Enter fullscreen mode Exit fullscreen mode

installation of nodemon

npm i nodemon
Enter fullscreen mode Exit fullscreen mode

nodemon is a tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.

Run express server on: localhost:3000

Image description

send json: localhost:3000/jsonexample

Image description
path is a inbuild module
we can call directories

Image description

params

The req.params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id. This object defaults to {}.
http://localhost:3000/api/products/3

Image description

query
The req.query property allows you to access the query parameters from the URL of an incoming HTTP request. Query parameters are key-value pairs included in the URL after the “?” symbol, and they are separated by “&” symbols.
http://localhost:3000/api/v1/query?search=r&limit=2

Image description

Basic crud operation
modules

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

//app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

let books is a arr obj

let books = [
    {id:1,title:'Book 1',author: 'author 1'},
    {id:2,title:'Book 2',author: 'author 2'},
]

Enter fullscreen mode Exit fullscreen mode

read

app.get('/', (req, res) => {
    res.json(books)
})

app.use(express.json())

Enter fullscreen mode Exit fullscreen mode

create

app.post('/books', (req, res) => {
    console.log(req.body)
    const newBook = req.body;
    newBook.id = books.length + 1;
    books.push(newBook);
    res.status(201).json(newBook)

})

Enter fullscreen mode Exit fullscreen mode

update/put

app.put('/books/:id',(req, res)=> {
    const id = parseInt(req.params.id)
    const updatedBooks = req.body
    const index = books.findIndex(book => book.id === id);

    if (index !== -1) {
        books[index] = { ...books[index], ...updatedBooks }
        res.json(books[index])
    }
    else {
        res.status(404).json({error: "book not found"})
    }

})

Enter fullscreen mode Exit fullscreen mode

delete

app.delete('/books/:id', (req, res) => {
    const id = parseInt(req.params.id);
    const index = books.findIndex((book) => book.id === id);
    if (index !== -1) {
      const deletedBook = books[index];
      books.slice(index, 1);
      res.json(deletedBook);
    } else {
      res.status(404).json({ error: "book not found" });
    }
})

Enter fullscreen mode Exit fullscreen mode

port

app.listen(3000, () => {
    console.log('server is running on port 3000')
})
Enter fullscreen mode Exit fullscreen mode

but this is not a good way to operate CRUD operations
there is a better way
folder structure

Image description

index.js

const express = require('express')
const app = express();
const bookRoutes=require('./routes/bookRoutes')

app.use(express.json());
app.use('/',bookRoutes)

app.listen(3000, () => {
    console.log('server is running on port 3000')
})
Enter fullscreen mode Exit fullscreen mode

bookController.js

let books = [
  { id: 1, title: "Book 1", author: "author 1" },
  { id: 2, title: "Book 2", author: "author 2" },
];

//read
const getBooks=(req, res) => {
  res.json(books);
}

//create
const createBooks= (req, res) => {
  console.log(req.body);
  const newBook = req.body;
  newBook.id = books.length + 1;
  books.push(newBook);
  res.status(201).json(newBook);
}

//update /put
const updateBooks= (req, res) => {
  const id = parseInt(req.params.id);
  const updatedBooks = req.body;
  const index = books.findIndex((book) => book.id === id);

  if (index !== -1) {
    books[index] = { ...books[index], ...updatedBooks };
    res.json(books[index]);
  } else {
    res.status(404).json({ error: "book not found" });
  }
}

//delete
const deleteBooks=  (req, res) => {
  const id = parseInt(req.params.id);
  const index = books.findIndex((book) => book.id === id);
  if (index !== -1) {
    const deletedBook = books[index];
    books.slice(index, 1);
    res.json(deletedBook);
  } else {
    res.status(404).json({ error: "book not found" });
  }
}

module.exports = {
    getBooks,createBooks,updateBooks,deleteBooks
}

Enter fullscreen mode Exit fullscreen mode

bookRoutes.js

const express = require('express')

const bookController = require('../controllers/bookController')

const router = express.Router()

router.get('/books',bookController.getBooks)
router.post('/books',bookController.createBooks)
router.put('/books/:id',bookController.updateBooks)
router.delete('/books/:id', bookController.deleteBooks)

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

check out in github:

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay