DEV Community

loading...
Cover image for Building server with express

Building server with express

Mayur Aitavadekar
I enjoy writing Javascript libraries, creating websites. Currently, I'm specialising in React and Node.
・4 min read

I’ve divided this article into three parts. In the first part, I’ve explained HTTP. In the second part, I’ve explained basics of express and finally I’ve written about middleware. So here you go..

HTTP guide 🌎

HTTP is hyper text transfer protocol which is one of the most popular protocol in the internet. HTTP works on request and response cycle from client to server and server to client. Every request is independent of other and hence it is also called as stateless protocol. Let’s understand the format of HTTP request and HTTP response.

Format of HTTP request 👇

|--------------------|             
|   request line     |  
|--------------------|     
|   request headers  |           
|--------------------|    
|   request Message  |     
|        body        |     
|--------------------|
  • Format request line 👇
request-method-name<space>request URL<space>HTTP version
GET /signout HTTP/1.0
POST /signin HTTP/1.1

Now, lets talk about HTTP request methods. Following are HTTP request methods using them you can interact with server over HTTP.
GET : to get resources from server.
POST : to send resources to the server.
PUT : to send data to server to update existing resource.
HEAD : to get resources from server without response body. Only request-line and request-header will be fetched.
DELETE : to delete specified resource in the server.

  • Format of request headers 👇

Request headers are in the form of key-value pairs. Request header is nothing but metadata of entire request.

Host : www.abc.com
Connection : keep-alive
Accept-encoding : gzip, deflate, br
Accept-Language: us-en, fr, cn
Accept : */*
Content-Type : application/json
  • Format of request body 👇

The HTTP requests messages can be of type depending upon what you specify in HTTP header content type. They can be json, url-encoded, form-data, XML, text, etc.
Now, let’s understand what is the format of HTTP response.

Format of HTTP response 👇

|--------------------|             
|   status line      |  
|--------------------|     
|   reponse header   |
|--------------------|     
|  response Message  |     
|        body        |     
|--------------------|
  • Format of status line 👇
HTTP-version<space>status-code<space>reason-phrase
HTTP/1.1  200  OK
HTTP/1.0  404  NOT FOUND
  • Format of response headers 👇 Response headers are similar to request headers. They are in the form of key-value pairs.
Date : Thu, 02 Apr 2020 10:29:02 GMT
Connection : keep-alive
Content-Length : 252
Content-Type : application/json
  • Format of response body Like request message’s body, response message’s body can be of any type such as json, text, html, etc. It basically depends on how developer wants to fetch the data from the server. Remember those HTTP response codes 😺.

Express.js 🤔

Installing Express over the Node.js is simple. Click here to see how to install.

Alt Text

Express is small, fast and minimalist Node.js web framework. It is mainly used for designing and developing back-end/server-side of web apps.
Here is simplest server developed using Express.

Alt Text

Above code is very much self explanatory.
app’ instance can call the various methods in express library. These methods include HTTP requests( GET, PUT, POST,DELETE,HEAD), use(), listen(), etc. Also if you include any third party libraries, ‘app’ instance will execute their methods too.

// EXECUTING HTTP GET REQUEST
app.get("name-of-route",callback-function);
// START LISTENING THE RESPONSE OF REQUEST ON THE SPECIFIED PORT
app.listen(PORT, callback-function);

Structure of Callbaks in Express

(req,res) => {
    /* 
        ... server-side operations
    */ 

    res.send("sending appropriate the response"); 
}

req and res parameters in callback function are request and response in HTTP which we discussed in the first part.


Express Middleware 🙌

As clearly mentioned on official website, ‘express is routing and middle-ware web framework.’ Handling middleware is one of the core functionalities of Express.

Alt Text

In simple language, whatever functions are written in between request-response cycle, they are known as middleware functions. Notice ‘next’ keyword which is necessary to pass the execution from one middleware to another. This keeps cycle running otherwise you will get error. Now, one thing to note here — In custom middleware from third parties, you need not to write next() because it automatically includes it from their source code.

Following are some of the types of middleware and there names are self explanatory. When building large scale applications, we can include these middleware in above server code.

  • Application middleware
  • Third Party middleware ( body-parser, cookie-parser ) You can install these using npm.
  • Built In middleware
  • Error Handling middleware
  • Router Level middleware

You can learn a lot by reading official docs on express.

Now, let’s write simple middle-ware so that you can get basic idea about how does the middle-ware works? I’ll include the code in above written code and Then run the server.

Alt Text

After running the above code, we get the following output on route “/” which is starting point of web app.

Alt Text

Then, we get following output on route “/client”. Here, first, client pass the execution to the middleware. You can see in the console. There will be message “the middleware is running”. After it’s execution the client will run and we can see output in the browser.

Alt Text

Now, depending upon requirement of designing the back-end of web application, you can write middleware in web application.
That’s it. I hope you’ve got rough idea for building server-side / back-end of apps using Express.js.

Happy Coding!! 👊 😄

Discussion (0)