Building a CRUD app with Node, Express and LowDB ( Beginner )

What is CRUD?

Dennis Grosch
10 min readJan 7, 2021

CRUD is an acronym for Create, Read, Update and Delete. It is a set of http methods to execute on the server ( API ).

  • Create ( POST )
  • Read ( GET )
  • Update ( PUT )
  • Delete ( DELETE )

What is ExpressJS?

Express is a web application framework of NodeJS which gives robust features for web and mobile applications.

What is LowDB?

LowDB is a Small JSON database for Node. This is used to store your data used for your web application.

Let’s build a web application

Prerequisites

You’ll need some knowledge on how to use the Terminal.

Now let’s check if you have NodeJS installed on your system. Open your Terminal and run the following command:

$ node -v
node version terminal

When you not get a version number you have to install NodeJS. To install NodeJS you can download the installer from the Website or download it with a package manager Mac and Windows.

Getting Started

Now create a folder for the project. It does not matter where you locate the folder. After you’ve created the folder, open the folder with the Terminal and run npm init. This creates a package.json file that contains all the information about your project ( Name, Version, Dependencies, … ).

Just hit enter through the menu. You can find more information here.

Creating the Server

First, we have to install ExpressJS.

$ npm install express

In your package.json under dependencies you can find express

package.json

Now we create the file server.js with the command touch server.js and inside the file we add

server.js

Now, run node server.js and go to localhost:3030 in your browser. You should the a message Cannot GET / . That is a good sign. It means we can now connect to the express server.

Adding Nodemon

Nodemon will restart the server automatically when you change something in your server files.

$ npm install nodemon --save-dev

We use --save-dev flag here to add nodemon as an devDependency in the package.json .

package.json

Now we have to add a script to package.json . This let’s us run nodemon server.js .

package.json

Now you can run npm run dev to start the server with Nodemon.

LowDB

First, we need to install LowDB with npm.

npm install lowdb

Once you installed lowdb, we can add it to our server.js

After const express = require(“express"); add:

server.js

Now we define our default data ( This is the data that is added to the Database JSON when it will first created )

We have to ignore the db.json on nodemon that will be created with lowdb so we don’t get a infinte loop. Add this to the dev script in the package.json

--ignore 'db.json'

Read ( GET )

So now we can at the Read methods. In Express, we handle this with the get method.

app.get(endpoint, callback)

endpoint is the url. This is the value that comes after the domain name.

  • when you visit https://crud-tutorial.com/express/ . Then is crud-tutorial.com the domain name and everything after this is the requested endpoint /express

callback tells the server what it has to do when the endpoint matches. It takes two arguments: request and response . We will use req for request and res for response .

app.get('/', (req, res) => {    res.send('Hello World');})

To get all posts we use a get endpoint and send back the posts from the database.

This means we get all posts with db.get and then save it to the const posts , after this we send the posts data with res.send .

To test it open your browser and go to localhost:3000/posts and you should get as response:

[
{
"id": 0,
"authorId": 0,
"text": "This is the first post"
}
]

Next, we’ll add a index.html page served by express. To do this, we use the sendFile method that comes with the res object.

We don’t have that files yet. Let’s create it.

$ touch index.html

And then we put this html code inside:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>CRUD APP</title></head><body><h1> THIS IS THE HOME PAGE </h1></body></html>

Restart the server and go to localhost:3000 .

Browser

Create ( POST )

You can send post methods with html <form> elements.

Let’s see how to use <form> elements to send data to the express server. Later we’ll see how we send post data with Javascript.

The form element need three things:

  • An action attribute to tell the browser where to send the request
  • A method to tell the browser what kind of request to send
  • A name attribute on the <input> elements to define the fields to send

Let’s see it in action:

Then we can handle the POST request with the post method from express.

Restart the server and go to localhost:3000 . Then fill the form and click the submit button. Now you should see in the terminal POST — /author .

To handle the data send by the form, we have to add body-parser.

$ npm install body-parser

body-parser is a middleware to parse incoming request bodies. Express lets us use the middleware with the use method.

const express = require("express");const bodyParser= require('body-parser');

and

const app = express();app.use(bodyParser.urlencoded({ extended: true }));

The urlencoded method within body-parser is to extract data from <from> elements and add them to the body property in the request object.

To get the data we can use req.body .

You should get following after submit the form in the terminal

{ name: 'test' }

Now we can save this to the database and for this we use the write method form lowdb.

  • we get the name from req.body
  • to increment the id we get the last element from the database and increment the id by 1
  • we use the push method to add the new author and the write method to save it to the database
  • res.redirect send the user back to the / path in the browser

Now when you submit the form the new author will be added to the database you can check it when you open the db.json

db.json

Show posts in HTML

We cannot serve the index.html file and add dynamic content. We have to use a template engine for this operation. Popular engines are Embedded Javascript, Pug and others.

Here we will use the Embedded Javascript (EJS).

First, we need to install EJS

$ npm install ejs

Next we need to set the view engine to ejs . This is to tell express we’re using EJS as template engine.

Then we will use the render method from express. It has the following syntax

res.render(view, locals)
  • view is the file name to render. This file has to be located in a views folder
  • locals is the data passed to the file

Let’s create a new view.

mkdir views
touch views/index.ejs

And copy everything from the index.html to the index.ejs . Now we use res.render to show the index.ejs file.

When you refresh the browser you should still the the same page.

We added the posts data to the index.ejs to render it we can use variables between <%= and %> tags.

You sould see something like:

We need to loop through the posts. For that we can use a for loop. To do this we add for between <% and %> .

Update ( PUT )

To update data we use PUT . Like POST it can be triggered with JavaScript or a <form> .

Now we will use JavaScript to update the post text.

First we need to add a button into index.ejs

We also need to create a external JavaScript file to execute the PUT request. The JavaScript file will be located in a folder called public .

mkdir public
touch public/index.js

Now we have to tell express that we want the public to be public accessible.

app.use(express.static('public'))

We can now add the index.js file to index.ejs on the bottom of body

  <script src="/index.js"></script>
</body>

Next, we’re sending the PUT request when the button is clicked

public/index.js

For this we can use the Fetch API that comes with modern Browsers.

fetch(endpoint, options)

For use we use the endpoint /posts and the method put

We need to tell the server that we are sending JSON data by setting the Content-type to application/json and in body we are sending out data.

Our server does not accept this JSON data at the moment. We can use body-parser fro this.

app.use(bodyParser.json())

Next we can create the put method in our server.

{ id: 0, text: 'Random Text' }

Then we have to update the data in the database to the new text.

  • we use find to get the post with the same id
  • assign is to set a value to a new one
  • res.json send a JSON back with the message Successful Changed

When we click the button and refresh the page the text has changed.

Next we can handle the response from the server via then .

You should see the message in the browser console.

Now we can add some different phrases and update the DOM to the the text changing.

The random text data
Get a random string from the phrases array
Reload the page
Final code

Delete ( DELETE )

This is similar to the Update from before.

First we need to add a delete button.

<button id="button">Replace first post with random text</button><button id="delete-button">Delete first post</button>

Then we will trigger a DELETE request through fetch . Add this under the update button part in index.js

Then we have to handle the delete on the server

Now when you hit the delete button the first post will be gone.

Make it final

The final step is to make the app look better and have all operations. But this part I leave to you.

  • Add a post and set authorId from a select field
  • show all authors
  • remove author
  • and much more

Wrapping Up

We covered CRUD, Express and LowDB. You have all learned you need to know about creating simple crud applications. Now you can make your own thoughts and build your own idea.

Stay home, stay safe!

--

--