Express.js Server

Express.js Server

·

4 min read

This is a quick tutorial on starting a server with Express.js

Before we jump into creating a server in Express.js. Here is some brief overview and some resources.

Node.js

Node.js is an asynchronous event-driven platform that allows you to build Javascript backend application. There are many frameworks ( a framework is a structure to build software) built on the Node.js architecture. In order to run Express.js, Node.js needs to be install first. It is recommend to choose LTS for downloading.

Once you have installed Node.js, go into your terminal enter "node" in the command prompt.

C:/Users/Jose>node

node .PNG

This confirms the node has been installed in your computer. Press control c or type '.exit' to exit the Node program.

Express

Express.js is a web framework that lets you build scalable web applications. Express is a layer build on top of Node.js. This adds HTTP request method, able to add "view" rendering engines, and process "middleware" request handling.

After downloading Node.js go to terminal and select a directory where want to save your project. On the command line make a folder and name it 'expressServer' and cd into that folder. (Windows command prompt).

mkdir expressServer && cd expressServer

On the same directory initialize the project by typing:

npm init -y

npm is a standard package manager for Node.js Javascript platform. For more information on npm packages npmjs.com

This will create a package.json file on the root of the directory.

nodePackage.PNG

Now the project is really to install npm packages. Type this on the command line:

npm install express

Create a file name index.js, type on the command prompt:

touch index.js

Open your favorite code editor. If you have visual studio code then type on the command prompt.

code .

Your file structure should like this.

file.PNG

Inside index.js type this line:

const express = require('express');

This line will call the express module in which returns an object with all Express.js application.

const app = express();

The code snippet above allows for implementation of all objects available to variable called app.

HTTP method

HTTP stands for Hypertext Transfer Protocol. It is a protocol for fetching resources such as HTML documents. Protocol means in computer science established the procedures to transit data between computers. Within http method the most popular are 'Get', 'Post, 'Patch', 'Put', and 'Delete'.

  • Get (read)
  • Post (create)
  • Put (update/replace)
  • Patch (update/modify)
  • Delete (delete)

In order for us to use the HTTP methods in our application, we are going to use methods called get from the Express.js module.

'app.METHOD(PATH, HANDLER)'

First lets try method from Express called get to read data sent to us. 'app.get()'.

Second lets apply a path. This sends the information to the path server. For this illustration we will be using localhost therefore the path is '/' which means the home page.

Third lets handle the information given or received from the server. It usually take two arguments. The first parameter is the req short for request. What are you requesting from the server ex. user id, forms... The second parameter is the res short for response. It usually means reading from server. Under handle we are going take res and apply a method called send. A list of method for res can be found here expressjs.com/en/5x/api.html#res

When applying send method, the send method takes in a body and the parameter just be a Buffer object, String, Array, Object or Boolean. For our illustration purpose we are going to put in a html tags as string. The String parameter sets Content-Type to “text/html”:

app.get('/', (req, res) => {
         res.send('<h1>Hello to all.<h1>')
});

Finally, now going to use a method on our application (app variable). The method is called listen. This method is to bind and listen the connections between the host and port.

app.listen([port[, host[, backlog]]][, callback])

In order to verify that the connection is successful for our callback (callback is when a function executed after outer function has finished executing). We are consoling our success. The port can be assign to any port ex. 4000, 3000. If not then the application is going to search for an open port.

app.listen(3000, () => {
        console.log('Server connected')
});

Now executed the program under the same directory type this on the command line:

node index.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
         res.send('<h1>Hello to all.<h1>')
});

app.listen(3000, () => {
        console.log('Server connected')

Then you should see on the command prompt 'Server connected'.

Link to the code github:

github.com/lauchRocke/expressServer

Here are some additional resources.