Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
George Anderson
Frontend and backend development guru, lover of all things computer... and cats! Hopes to make your coder life a breeze by sharing some tips and tricks of the trade.
Posted on Mar 4th 2019

Web development has never been more exciting than now, with the introduction of new technologies and techniques, thanks to the dynamism and evolution of JavaScript. Now a web application can be configured using only JavaScript. This is made possible through the introduction of Node.js, which can be used on the server side to manage data, and also the creation of several JavaScript frameworks, such as React.js, Angular, and Vue.js, which manage and control the client side of the application.

In this article, we will be learning how to build a simple shopping cart app, using React.js as the frontend framework, and a backend server built using Node.js and Express.js. 

Below is a preview of what we will be building:

Configuring the Development Environment

For this tutorial, I will be using the Eclipse IDE with the CodeMix plugin installed.

Fall in love with React all over again, or discover it for yourself, with CodeMix – an Eclipse plugin that lets you add VS Code-compatible extensions directly into Eclipse. Superior IntelliSense, validation, navigation, as well as JSX and debug support for React development – all without leaving your IDE.

Creating a React Project using CodeMix

We can now create our application using the CodeMix Project Wizard. We’ll be using the latest version of all the tech libraries and stacks as at the time of this writing. To create a new React Project Navigate to File> New > Project > CodeMix > React Project.


Now click Next and enter your project name on the next screen. Finally, click Finish to continue with the React project creation.

Let’s install some modules which we will need in building the application. Open the integrated Terminal+ in CodeMix 2.0. Alternatively, it can be opened using the command Ctrl + Shift + P, as shown below, to run the following command: 

These are the technologies we will be using for our app:

  • Cors: it provides a middleware to handle cross-origin resource sharing.
  • Axios: it is a Promise-based HTTP client used to communicate with the Node server.
  • Express: it is a Node.js module that simplifies the creation of a node server.
  • JsonWebToken (JWT): it is a compact and self-contained way for securely transmitting information between parties as a JSON object.
  • React Router: it is used in handling the application routing.
  • Bootstrap: it is a CSS framework.

Setting up the Backend Server 

In this section, we will be building the Application Programming Interface (API) for the application. First, we create an api folder in the root folder of our project. This folder will contain the express backend. Next, we proceed with creating a server.js file which will contain the server configuration.

This server.js file contains four routes, the first of which returns an array of products loaded from the data.js module (which also contains an array of valid users). 

The second route is a post route that accepts a cart string, parses it, and generates the list products on the cart, along with their quantities.

The third is the login route that authenticates the user, i.e. verifies the user is valid (registered). It generates a JSON web token that expires in 2 hours. The generated token is used to bypass the login middleware (which we will create next).

The fourth route is a get route guarded by a middleware. This route requires the request to be authenticated, i.e. it provides a valid token. This middleware checks that the token was generated using a valid user. It also checks to confirm that the token is not expired. To create the middleware, we make a middleware.js file in the api folder, as shown below:

If a request is made to a guarded route without a valid token, the middleware intercepts the request and returns a 401 (Unauthorized) error.

Next, we include a script in the scripts object in the package.json file, which we will use to start up the application API:

With that, we have completed the development of the API server, which we can then run using the command below in the integrated terminal:

Setting up the Front End

Now that we have the application’s back end running, let’s begin developing its front end.

From the root of the project, we will open a new terminal using the Ctrl + Shift + P command. In the terminal, we will run the following command to start the React application:  

This application will be styled using bootstrap. This can be achieved in several ways, one of which is to install the React bootstrap module, as we had previously done. We then import it into the root React component, i.e. the index.js, as shown below:

Let’s create a repository.js file which will contain all the interactions with the backend server, using the axios module.

The getProducts method fetches all the available products from the server.  The getCartProducts fetches all the products in the cart, by passing the cart string to the server. This cart string is parsed to an object, with its keys as the product ID, and the values as the requested quantities. The login method submits the user credentials to the backend server. It also stores the generated token along with the token’s expiration time in the local storage of the browser upon a successful request. The pay method is only available for authenticated users because it requires a valid access token. The final method is used to verify that the user is authenticated by checking to see if there is a valid token that is not expired.

Creating Components

Let’s proceed with creating a src/components folder which will contain the application’s components.

In the application, we will be creating six other components which include Login, ProductItem, ProductList, CartItem, Cart, and Checkout, in addition to the root App component.

The JSX editing capabilities in CodeMix make it easy to work with React code. Just take a look at the GIFs below to see how you can take advantage of the editing capabilities in CodeMix, as you work your way through these components.

First, let’s create the Login component. 


This component gets the username and password, passes it on to the backend server when the form is submitted, using the login method from the repository module, and redirects the user to the home URL upon a successful request.

Let’s create the ProductItem component, which we will be used to render each product on the product list.

The addToCart method adds the given product to the cart which is an object stored in localStorage as a string using the JSON.stringify method. This method converts the string back to object using the JSON.parse method or creates a new object if no item is found. The product is then added, and the cart is saved back in localStorage.

Let’s create the Product List which uses the ProductItem component to render the list of products. 

This component fetches the array of available products using the getProducts from the repository module in the componentDidMount life-cycle provided by React.

Let’s create the CartItem component which will be used to render each product on the cart.

This component uses the remove method provided as a prop to remove the item from the cart completely. The remove method is provided by the parent Cart component which we will be creating next.

The removeFromCart method in this component is passed to the CartItem component. It deletes the product from the cart on the localStorage and removes the product from the list products to be rendered. The Cart component also provides a clearCart method which removes all the items on the cart (this is done by deleting the cart from the localStorage).

Let’s create the Checkout component. This component will only be rendered if the user authenticated (logged in).

This component loads and renders all the products on the cart, much like the Cart component. It also provides a pay button which will in this case alert a message to proceed to payment after accessing a secured route on the backend server. This is made possible by the access token attached to the request in the pay method in the repository module. It also redirects unauthenticated users to the login page.

Now that we have all the required components, we can proceed with editing the root App component:

In this component, we create, control, and manage the application’s navigation. Here, we render the navigation bar which in turn renders several links using the Link tag provided by react-router-dom, which is roughly equivalent to the HTML “a” tag. It renders the Login link when the user is not logged in, and renders Checkout and Log out links if otherwise.  The log out button triggers the logOut method which deletes the access token and renders the application with the user logged out. This component also manages the application routing, i.e. it chooses which component to render for each route or link. To enable the use of react-router-dom components in the application, we need to wrap app component in a BrowserRouter component.

Congratulations! We have just successfully built the entire application!

To recap the application start-up process, to run the application, we need to run both the back end and front end of the application. To start the backend API server of the application, we use the command:

To start the front end, use the command below: 

After those have been successfully started, we can visit http://localhost:3000 in our browser to view the application.

In Closing

Over the course of this article, we’ve built a simple shopping cart with an Express back end and a React front end. We’ve kept this application simple to demonstrate core Express and React concepts. Next steps would be to change the back end to interact with a database instead of static data, and use technologies, such as Flux, Redux, Mobx, etc., to make the front end more efficient and modular.

The code for this application is available here.

 

Related Posts

React Image Upload – How It’s Done File upload is a very important feature of web applications: it helps facilitate actions like setting a user's profile picture, setting up dynamic galleries, remote file storage, and file sharing, among many other functionalities. In this article, we will be looking at file upload (more specifically, images), using React web framework, to a Node.js...
React Tutorial: Create and Debug an App in Eclipse... Making React run properly in Eclipse can be a really big headache…or an amazingly cool experience with CodeMix! CodeMix integrates the best of the VS Code world into Eclipse, such as support to create and debug React applications. Follow this React tutorial to quickly create and debug an app in Eclipse with CodeMix:Create Your App Make sure you hav...
Fullstack Vue App with Node, Express and MongoDB Much of application development, including web applications, has to do with CRUD - creation, reading, updating and deletion of data. Today, we will be building a fullstack Vue note-taking application and showing you how to perform the aforementioned processes, using Node.js running the Express.js framework for the back end, and MongoDB to store our...
CodeMix 2.0 Is Out! Pipelines, CodeMining and More It’s fall, and we’ve just dropped our hottest release of the year, CodeMix 2.0! Well past the CodeMix 1 growing pains, we’re hitting prime time with this release, which includes the best features from Webclipse 1.x, as well as exciting new modern web tech that CodeMix brings to Eclipse from VS Code.Exciting CodeMix CapabilitiesCodeMix is an Eclipse...