# Getting Started With ExpressJS For Backend Development.

Backend web development can be complicated, especially when you do not have the right resources to learn. NodeJs for backend development is superb but the more you work with NodeJS, the more you hope there's some kind of framework to help make some of the repetitive configuration tasks less boring. again, NodeJs is amazing, don't get me wrong, but it's not simplified enough for a newbie, especially the configurations, and that's why we have a framework that hides away a lot of those annoying cumbersome configuration setups, which makes setting up our server so seamless that we can focus on the core functionality of our application, which is to listen to requests from the browser and send back a response from our server.

So, first of All, What is ExpressJS ?

ExpressJS is a minimal and flexible NodeJS web app framework designed to make developing web apps and APIs much faster and easier. it's almost unfair how easy it is to spin up a server with the help of ExpressJS. while ExpressJS is not a part of NodeJS, it is not a built-in module or anything like an HTTP module, it is a standard when creating web applications with NodeJS.

To get started with ExpressJS, we need to install the package (I'm assuming you are familiar with NPM) open the integrated terminal in your visual studio code, navigate to your root path, write "npm install express --save" to have the package added to your NodeJS project. After installation, we get access to the ExpressJS object. We create an instance of the express object by importing it into our file and instantiating it. And after instantiation, we have our server instance with a bunch of cool methods from the express library that makes our development experience smoother as opposed to doing everything from scratch with vanilla NodeJS. e.g creating the HTTP module from scratch, calling the createserver method and a lot of that configuration stuff, setting default headers, express handles most of that for us....( cool, right? )

some of the methods we'll get straight out of the bag from ExpressJS library are;

1.  The "GET" method
    
2.  The "POST" method
    
3.  The "PUT" method
    
4.  The "DELETE" method
    
5.  The "LISTEN" method
    
6.  The "USE" method
    
7.  The "ALL" method
    

We have a couple more methods available to us but as a backend engineer whose primary job is to create APIs, Handle requests from the browser, and send back responses, these are mostly the methods we'll be using.

Just by looking at the method names, we can get an interesting idea of what they do. they are mostly self-explanatory. but I want to briefly talk about each one anyway.

The first 4 methods represent HTTP verbs. when we talk about the HTTP request and response messages, one of the things we'll be looking at in the HTTP request message is the HTTP verb and which represents what a user is trying to do, whether read a data, insert data, update data or delete data.

1.  GET method: All browsers perform a get request by default. when you open your favorite browser and try to go to a website the browser is performing a get request. sending a get request to the server to get some resources hosted on that server. and the GET method from ExpressJS makes handling the request and sending back responses easy.
    
    This method takes 2 arguments, the path(that holds the resource user is trying to get) and a callback function that executes to handle that get request. The callback function also takes 2 arguments( req and res), they represent the request and the response objects from the browser and the server respectively. the request object holds information about the request from the browser(URL the request is coming from, message, header) and the response object, as you might have guessed, we get access to that in ExpressJS to send a response back to the browser. we can have as many get requests as possible handling different paths (routes) to get different resources on our server.
    
2.  POST method: This handles requests from the browser to send data/resources to our server. say we have a registration form where a user inputs their name and email, and the information is sent back to the backend using a POST method. we handle and get access to data being sent to our server with the post method.
    
3.  PUT method: This is just a method to update some resources that the user might have sent to the server. where we not only get some information on the request body to update resources, we also send back responses about the updated resources
    
4.  DELETE method: as simple as it sounds, this is used to send a delete request from the browser to the server, to delete some resources on the server
    
5.  LISTEN method: This is a method we use to listen to requests from the browser. we pass in the port we want our server to be listening on as an argument to the method e.g 5000. and a port is just a communication endpoint for our HTTP server. an endpoint where our frontend and backend communicate. I believe port 0-1024 has been taken by other programs so we can't use them but in local production, the port is usually an arbitrary number and you can use basically whatever you want.
    
6.  USE method: this is responsible for middleware, a very crucial part of ExpressJS. we use this method to pass in middleware to all or specific routes. as opposed to manually adding middleware to each route which is tedious and could be time-consuming depending on the number of routes we have. we can call the USE method and pass in a route(optional) followed by the middleware function as arguments and it applies the middleware function to the routes we specify. Another important thing to understand about using the use method is that the order matters, if we place our USE method that's holding a middleware, below a route, that route automatically get omitted and the middleware won't get applied to that route. so it's recommended to always place all of our USE functions at the top of our page, specifically, above all the routes. We can also execute multiple middlewares in the use method, we place the middlewares we want to execute in an array and pass it into the use method as an argument. e.g app.use(\[authorize, logger\])
    
7.  ALL method: Let me paint a scenario, if the user(browser) tries to access a route/resources that do not exist on our server, the default response that ExpressJS sends back is simple (cannot get /path) text, which is a 404 status code, a bad request, to send a better error or a customized error message because they are obviously trying to access a resource that does not exist. The All method handles all HTTP routes on our server, and that makes it perfect to set up an error message response that we send back to the browser. it takes 2 arguments, a route and a callback function. We can pass in \* to represent all routes in our app and the callback function takes res and req objects(of course) using the response object(res), we can send back a "resource not found" message and if a user tries to access a resource that's not available on our server, they get that instead error response of the default express error.
    

In most cases, we typically use ExpressJS to either set up an API(application programming interface) or set up templates with server-side rendering.

Depending on what we are trying to do, we need to know how to configure our app to send and receive data.

To use ExpressJS to set up an HTTP interface(API) to interact with our data, we have to configure data to be sent back with our response using JSON, we have a res.json() method from ExpressJS that does all the heavy lifting for us e.g setting content-type, stringify our data. and we have a middleware that parses incoming requests from the frontend and allows us to get access to the JSON data. (express.JSON). so we can get and send data in JSON format.

NOTE: the main function of an API is that our server provides data and any frontend app that wants to access and use our data, can simply perform HTTP requests to our API and use our data. (that's why our data has to be sent back and forth with JSON)

To use ExpressJS to set up server-side rendering where we will set up templates and send back the entire HTML, CSS and javascript ourselves, we have a RENDER method to do that.

# Middlewares In ExpressJS

Middlewares are functions that execute during the requests to the server. each middleware function has access to the request and response object. middlewares are a very important part of ExpressJS because of the flexibility they give us. middlewares are everywhere in ExpressJS, you can even make an argument that express applications are nothing but a bunch of middleware mashed together to make one big application. so, middlewares are not one of those topics you can just skip or avoid, it's absolutely important to grasp the idea behind it and know how to use it. Another reason why the middleware is so powerful is that we can set up a property in the middleware and attach it to the request object and so, any routes that are using the middleware also get access to whatever properties we might have set up in the middleware (how cool is that?). Middleware truly allows us to structure our applications like lego blocks where we get pieces of functionalities and combine them to get a fully functioning express server. we also have a couple of built-in middlewares from ExpressJS to make our development experience smoother. e.g express.static (makes our files static so that they are publicly available), express.json (to parse our JSON files at the frontend and make them available)

Another important thing to always remember about middleware, to prevent our app from being stuck in limbo, we need to always call the next() function to pass current middleware to the next middleware, unless you're terminating the entire cycle with a response in the middleware function. . . we also have third party middleware functions we get from npm. the bigger our ExpressJS application, the more middleware functions we'll most likely use.

# Route Parameters in ExpressJS

Say we have a situation where we have a list of products we are returning as a response to a get request coming from a route, and we want to be able to return a particular item with a specific ID as opposed to all the products, this is actually a common scenario in web development as a whole, where we want to get a specific user data or products. Problem is, we need a way to get the ID of the resources that's been requested on the request body to the backend so that it can be used to write the logic to return the single product. Route parameters are the perfect solution for this. on the request object, we have access to the route parameters. whatever comes right after our path is what we are setting as parameters, it comes along with the request object as a string and we can access it on the request. params object. once we get the id back from the params, we can then use it to write the logic to find a specific product and because of that solution the route params from ExpressJS gives us, we don't have to hardcode values and set routes for each single products which is a very ineffective way of setting that up anyway. I like to think of route parameters as placeholders where the user passes data and using request params, we can access that data and use it to effectively solve that common problem of sending back a product/item based on the data(usually ID).

# Query String Parameters In ExpressJS

Query string parameters(URL parameters) are a way for us to send a small amount of information to the server using the URL. we usually use them as parameters to maybe query databases, filter results etc and it's really up to us to decide what parameters are accepted. we set it up by passing a property name e.g "search" after the API route, then a question mark, and then, a query parameter and a value. so we get to return data based on the property name and value we set up in our URL as a query string(cool). another interesting use for query strings is to set up paginations. we set up a property name, question mark and then key-value pairs that are supported by the setup. and of course, we can get access to the query strings in ExpressJS setup on the request query object(req.query)

# Routers in ExpressJs

This is an important middleware that allows us to group multiple routes. the express.Router() function is used to create a new instance of the router object for handling requests. also makes it easy to differentiate requests. In summary, setting up our projects with routers keep our file clean, and much easier to read.

# Controllers In ExpressJS

Controllers are functions that execute when a request to a certain route is made. they are the code that processes and outrightly handles requests. controller functions help keep our files lean, organized and easy to read.

As an ExpressJS newbie, Having a solid understanding of some of the methods and concepts I have written here, makes using ExpressJS much more enjoyable and helps improve your backend development skills in general.

Hope you learned one or two things.
