DEV Community

Swislok-Dev
Swislok-Dev

Posted on

What is Express.js?

Express is a nodejs framework built on top of the http module and is middleware based. Express has the ability to funnel requests coming through a uri chain and do stuff with it.

When the request comes through, express is able to perform actions, get data, check user auth, send status codes etc.

A basic get request looks like this:

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

const products = [
  { name: 'iPhone', price: 800 },
  { name: 'iPad', price: 650 },
  { name: 'iWatch', price: 750 }
]

app.listen(port, () => {
  console.log(`Server is listening on port ${port}`)
})

app.get('/', (req, res) => {
  res.send("Hello World!")
}

// GET request for all products
app.get('/api/v1/products', (req, res) => {
  res.json(products);
}
Enter fullscreen mode Exit fullscreen mode

To get this server running, use node index.js

Information can be sent back and forth between the routes and pages for the site.

const findId = (id, list) => {
  return list.find((el) => {
    return el.id === Number(id)
  })
}

app.get('/api/v1/products/:id', (req, res) => {
  const product = findId(
    req.params.id,
    products
  )
  // If the product is found
  if (product) {
    res.send(foundExpression)
  } else {
    res.status(404).send()
  }
})

Enter fullscreen mode Exit fullscreen mode

Full CRUD functionality can be configured right from express routes and help to control the smaller functions of the site further increasing the separation of concerns.

const getIndexById = (id, list) => {
  return list.findIndex((el) => {
    return el.id === Number(id);
  });
};

const updateElement = (id, query, list) => {
  const index = getIndexById(id, list);
  if (index === -1) {
    throw new Error ('must have a valid id');
  }
  if (query.id) {
    query.id = Number(query.id);
  } 

  Object.assign(list[index], query);
  return list[index]
}

// Update
app.put('/api/v1/products/:id', (req, res) => {
  const productIndex = getIndexById(req.params.id, products)
  if (productIndex !== -1) {
    updateElement(req.params.id, req.query, products)
    res.send(products[productIndex])
  } else {
    // respond with 404 not found code
    res.status(404).send();
  }
})
Enter fullscreen mode Exit fullscreen mode

To finish, we can add a delete request

app.delete('/api/v1/products/:id', (req, res) => {
  const productIndex = getIndexById(req.params.id, products);

  if (productIndex !== -1) {
    products.splice(productIndex, 1);
    res.status(204).send();
  } else {
    res.status(404).send();
  }
})
Enter fullscreen mode Exit fullscreen mode

All these and more can act as embedded functions that will run with the need for it to exist in the frontend source project while still be able to handle API requests without blocking down the backend source, or to give more customization to the frontend control.

Oldest comments (0)