NodeJS Express: GET request

The previous article describes how to display a list of conferences and how to filter them with AngularJS. A view would be nothing without data. Therefore the data is a hardcoded array in JSON format. However, this is not an approach for real-life application. Data is a dynamic part of an application, which depends on a user and any other aspects.

A goal for this article is an explanation of how to serve data for the view in a dynamic way. The dynamic approach is the implementation of another application responsible for serving data in the same JSON format. The app uses NodeJS, Express library, MySQL database, Sequelize ORM library.

HTTP, REST API and CORS

Let’s go through some knowledge about communication between a client (frontend app) and server (backend app).

HTTP (Hypertext Transfer Protocol) is a protocol for transferring data over the Internet. It specifies the data format, a response status, request methods, etc. Moreover, HTTP is stateless which means that every request is handled separately. Requests have own data, they don’t contain data from other requests.

REST (Representational State Transfer) API is an app that sends data in a format not related to UI, so it doesn’t send HTML documents. It sends data in JSON or XML.

CORS (Cross-Origin Resource Sharing) prevents from sharing data between client and server that are in different origins. Origin is a combination of protocol, domain and port. CORS policy provides an API a possibility to decide with which clients it will share the data. This is a common security mechanism in browsers.

MVC Design Pattern

MVC stands for Model View Controller which are parts of an app architecture. The view part can be implemented with another app. The situation is in this case – the view is Angular app and Express API contains the model and the controller parts.

As you can see at the below picture, the controller is a bridge between the view and the model. It is responsible for getting a request and return a response. In this case of REST API, a response contains data in JSON format. Representation of a data is the model.

nodejs express mvc

Environment Set Up

Install the latest Node.js version.

Create folder and type the following command:

It creates package.json which is a project configuration.

Then install express in this folder.

Install Sequelize library.

And install mysql2 library.

Create Server with Express

As it is an application which runs on a server, a first step of running NodeJS app is to create a server. To do this, paste a below code to the app.js file and run node app.js command.

It creates the server that listens on 5050 port of a local host.

Before creating a server, Express will register a middleware function. Middleware is a handler for requests. If any request occurs, it invokes the function. In this case, the function will be executed for each request.

The function sets headers that prevent CORS error. As the app needs only GET type of HTTP method, a header is set to allow only GET methods.

Middleware must call next() function to finish itself and let next middleware executes. The next one is the middleware registered in the next line of code.

Sequelize ORM

ORM (Object-Relational Mapping) is an approach to manage a database’s data in code. A library which implements ORM approach maps the data to objects and creates tables’ relations. Moreover, it provides CRUD (Create, Read, Update, Delete) methods and many more features that help working with database in code. Sequelize is an ORM library written in JavaScript.

What you need to do to create table and get data with Sequelize?

First of all, you need a connection with a database. In this case, the database was created with MySQL engine, but Sequelize offers integration as well with PostgreSQL, SQL Server, SQLite and more.

The first argument of Sequelize class is a database name, the second one is user name and the third is a password and the last one is a Sequelize configuration.

The database connection is necessary to create a table schema. I put the connection in a separate file and created a NodeJS module which can be now imported by using require.

Above code prepares schema for table conferences which has id, name, dateFrom, dateTo, columns. The model name is conference, but Sequelize will create a table with the plural name of the word. Furthermore, Sequelize generates correct plural for such words like ‘city’, ‘country’ etc.

The conferences table should have a foreign key to the cities table to have a relation with it. Additionally, the cities table should have information about the country. The following code generates such relations.

Last but not least, Sequelize must execute only one function to create the tables and their relations.

The sync() does the whole job. This is an asynchronous function which returns a promise. After successful execution, you can be sure that the database has everything that an app needs from it.

Controllers and Routes

As you already know the controller is a bridge between view and model.

Below function is a controller method for getting conferences. The request object contains query property which represents query string data. A query string is a string in URL after a query sign. For instance, URL https://devsoutput.com/?author=ewelina contains a query string with a key author and value ewelina.

The method returns the response object with status code 200 and data returned from the database. HTTP status code 200 means that controller’s method executed successfully.

Conference class is responsible for CRUD operations.

findAndCountAll is a Sequelize method that returns filtered records and a count of all records. This is really useful for filtering and pagination on a server side.

However how does a client reach to the controller method?

The router registers endpoints – the addresses for controller methods. In the below case calling localhost:5050/conferences will execute the method for getting conferences.

Routes must be registered as every middleware.

Conclusion

Express is a flexible library. Thanks to middlewares it gives a possibility to run features on each request or the chosen ones. The JavaScript feature – modules – give a solution to a group and divide a code in a lean way, for example, to implement MVC design pattern.

Sequelize is a powerful ORM library. It provides one function to return records and their count. With additional parameters, this function runs one SQL query which returns filtered and paged records with chosen columns. Default Sequelize behavior is lazy loading. It returns related records as well when ‘include’ parameter is passed to the function.

I recommend exploring Sequelize documentation to find out many more such useful functions.

If you want to check how architecture and the whole code of the app look like, go to my Github.

0 0 vote
Article Rating
Share on
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Marcin
Marcin
July 30, 2019 8:11 pm

Well done, thanks!