DEV Community

Cover image for Your first steps with Express.js
Eric The Coder
Eric The Coder

Posted on

Your first steps with Express.js

What is Express?

Express is a Fast, unopinionated, minimalist web framework for Node.js. It is also by far the most popular Node.js web framework.

What we can do with Espress?

  • Web Application: Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications

  • APIs: With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.

  • Espress is not a frontend framework like React or Vue. Express is a backend framework that will complement a frontend framework to build full stack applications

Express prerequisites?

To use Express we need a working version of node.js already install on our machine.

You also need to understand node.js basic concept. If you dont have this basic understanding, you can read this small series that cover all node.js setup and basic concept: https://dev.to/ericchapman/node-js-101-part-1-what-is-node-js-1529

Install and setup Express

First we will create a new folder and a start a new app, then we will install Espress. In your terminal execute:

$ mkdir discover_express
$ cd discover_express
$ touch app.js
$ npm init
$ npm install express
Enter fullscreen mode Exit fullscreen mode

Those command will create a new node app install with with Express packages.

Your first Node.js Server

We are now ready for our first line of code. Open app.js and type:

const express = require('express')
const app = express()
Enter fullscreen mode Exit fullscreen mode

This code will initialize the app variable as a new express object.

So now we can start the server:

app.listen(5000, () => {
  console.log('Server running on localhost:5000...')
})
Enter fullscreen mode Exit fullscreen mode

5000 is the port number. That value can be change.

Understand the basics of how your web browser communicates with the internet

To access a page on the internet, your browser must ask the server for the page it want (request), and then display that page to you (response). This protocol of requests and responses enables you view this page in your browser.

For example, when you visit facebook.com/about, your browser request the about page from facebook server.

Facebook server will then find and match your request path, will do the processing and send the response associate with this path.

Here are more examples of different url path.

root route: facebook.com
profile: facebook.com/profile
about: facebook.com/about
login: facebook.com/login

GET and POST request

Your browser can ask for a page but your browser can also send data to the server (ex. login form).

When the browser ask for information that's call a GET request.

When a browser send data to the server that's call a POST request

So asking for facebook/about page is a GET request.

But what if...

What append if the asked page is not present on the server. For example you ask for facebook.com/blabla

The server will include a status code with every response he send back to the browser.

If everything work as expected the status code is 200. If the page is not found the return status code will be 404.

For reference here a list of some HTTP status codes:
200 : OK (successful)
401 : Unauthorized
403 : Forbidden
404 : Not found
500 : Internal Server Error

I dont understand a word of what you just explain

It's totally possible and normal. It is very important you understand this base before going further.

Here a link to a more complet tutorial: https://academind.com/tutorials/how-the-web-works/.

First client/server communication

In the first part of this post we create a node.js server with an express app.

const express = require('express')
const app = express()
Enter fullscreen mode Exit fullscreen mode

We then made the server listen for incoming request:

app.listen(5000, () => {
  console.log('Server running on localhost:5000...')
})
Enter fullscreen mode Exit fullscreen mode

Now that the server is listening. We can create a route to match a potential incoming request path.

app.get('/', (request, response) => {
  response.send('Hello World')
})
Enter fullscreen mode Exit fullscreen mode

This server is waiting for a request at the route '/' (root path). Note that the route is waiting for a GET request. (app.get)

Once that request is receive, the server will send 'Hello World' as a response.

Let's test all this. First Launch your server. From the terminal type: node app.js

$ node app.js
Server running on localhost:5000...
Enter fullscreen mode Exit fullscreen mode

Then open your favorite browser and go to localhost:5000. Hello World should be display.
Hello World

It is possible to send a HTTP status codes with the response. That will indicate to the client that the request/response is a success or a failure.

app..get('/', (request, response) => {
  response.status(200).send('Hello World')
})
Enter fullscreen mode Exit fullscreen mode

Status 200 is the number for a successful request!

HTML response

The server we create just send a response in plain text (Hello World).

But it is possible to send back HTML or JSON.

HTML Response

app..get('/', (request, response) => {
  response.status(200).send('<h1>Hello World</h1>')
})
Enter fullscreen mode Exit fullscreen mode

You can now re-start the server. If your previous server is still running in the terminal. Press CTRL-C to cancel the server execution. You can now start the app to see the change.

$ node app.js
Enter fullscreen mode Exit fullscreen mode

If you refresh your browser at localhost:5000 you will now see Hello World but this time in big header h1 format!

JSON response

The server can also send back data to the browser. For example after a login the server can send back some user profile info.

One of the standard way to send data back and forth is JSON.

JSON (JavaScript Object Notation) is a standard text-based format for representing structured data based on JavaScript object syntax.

It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa)

JSON is often use with API. We will cover API in detail in the next lesson.

To send a json response in express is very easy:

app.get('/', (request, response) => {
    response.status(200).json({user: 'Mike Taylor', level: 'admin'})
})
Enter fullscreen mode Exit fullscreen mode

The .json() convert and send a javascript object {} as JSON.

Conclusion

WOW congrats! You just create your first Web Server!

That's it for today. Tomorrow the journey continue. We will start working on one of the most used case of express.js: building our first rest API... Stay tune!

Follow me on Twitter: Follow @justericchapman

Top comments (0)