Full Stack with Express JS (Node JS) and Template Engine (EJS)
Hi, back again to Basho Code (the place you can learn code for free) and now we will going to learn about how to make basic CRUD (Create, Read, Update, and Delete) with Express JS and the bonus is Filter. So, we will call it BREAD (Browse, Read, Edit, Add, and Delete).
Minimum Requirements you should have are JavaScript, HTML, CSS, Bootstrap, and JSON (because we will not use database yet for now). And also you need to have Coffee and Music Player (also speaker or earphone lol).
This tutorial will not use any database yet, instead we will use JSON and learn basic Node JS like Read File or Write File and you should know that this tutorial will so loooooooooooooooooooooooong, hahahahaha but don’t worry I just kidding, it will not long as you watching Korean Drama or Anime Series, here we go !!
So, my question is did you installed Node JS on your PC ? I use Ubuntu (Linux based) and I will reccomend you to use Linux or Mac, because I will not answer your question if you use Windows (beacuse I don’t know).
If you have read about Get in Touch with Express JS before, you should know your software requirement, and if you not read that yet, go there and read it !! Now !! This litte things is the requirement too.
I assumed that you was created your first project and also know about basic Express JS, so right now open your terminal and create new folder, after that type this again.
npm init --yes && npm install --save express ejs body-parser
Or you can type multiple times like this, but I prefer type once (just add && and separated with white space in npm install).
npm init --yes
npm install --save express
npm install --save ejs
npm install --save body-parser
We need to install express of course and why we install EJS and Body-Parser ? EJS is template engines that help us to write html code and put javascript code on it (you will know later) and body-parser is needed to catch the user input on form or something like that.
Now, we need to create a new JavaScript file, just call it app.js.
We need to import body parser, express and fs (stands for file-system, and default on nodejs) you can find the node js documentation, and you can learn there.
As always we need to execute express and define the port, after that we see that app will setting views to folder views and set view engine to ejs, then we will use body-parser and telling express to set the static to folder called views so client can download it from server (it will explain how client can see your front end).
How to do Read
You can also find the better implementation by reading on the official documentation, you should read and try it by yourself for better experience.
Programming is not about copy-paste, but thinking the algorithm and also read the documentation.
fs.readFileSync is the method from file-system, go to the node js documentation to get it more. We just use syncrhronous for the first time and in the future we will try to use asyncrhonous and learn about async await, promise, and callback (will very interesting). You see that the file we should import is inside of folder data, so we need to make new directory (folder) called data and create new json file inside of it (called series.json) and look like this.
And you know why we parse the data ? Try to find the answer at google (for your task) about JSON.parse and JSON.stringify (it will useful, trust me).
data
series.json
node_modules
blablabla
blablabla
blablabla
views
index.ejs
app.js
package-lock.json
package.json
Remember, we create index.ejs not index.html because we use template engine, ejs file can contain html and css too, so don’t worry.
Forget about README.md and .gitignore for now haha
The structure should look like that, and just give index.ejs default html (if you use vscode you can just press shift + 1 and enter, it’s called emmet).
app.get('/', (req, res) => {
res.render('index', { data });
});
Above code, like you learn before in get in touch with express.js is how to make route, and you know what ? res.render will render the view file called index because you passing index in first arguments and how about { data } ? data is the json file you parsed before and it will send to the views, so you can use that data inside of html, that’s why we need EJS to processing that.
Open the documentation of bootstrap and see the bootstrap CDN, we will use cdn for now but you can also install bootstrap if you want, for this tutorial I will use CDN, copy paste to the index.ejs we have.
We just need the CSS, okay! And put this to the head tags
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
Now open the EJS documentation, and you will see like this
You should read that documentation before continue this tutorial, not so long just one page. Then you will know about <% , <%=, <%-, etc.
You should find the table in bootstrap, and put that code on your index.ejs, but with the help from EJS you will see the magic lol.
With that starting code, you can run the app with type node app.js again (like we did in the last tutorial). Then you need to open browser and go to localhost:3000 again.
Yeaaaaaa, we have done to do Read (Read is how to implement logic that will give client possibility to see the data we have), how ? haha did you remember what is <% and <%= ? And also you need to do closing tag %>, you will know how to implements EJS if you read first and you try.
You will get nothing if you just copy paste and not try to think how that’s happen, trust me!
How to do Add
Now, we need to close our app in terminal by CTRL + C and then we can continue to code, why we need to do that ? Because Node JS is server side rendering, so they can’t automatically update when the code has been changed. But alternatively we can use auto-run by Nodemon. If our app is big, nodemon will help a lot. For now we will not use it because this is practice not working.
So, what will we do now ? Yeah, we will create new route and also another page which contain form for create data.
First, create an EJS file inside of views directory called add.ejs and then the file will contain this code
You will see the form, and button. In that form, we have action called “/add” and method “POST” that’s mean after the form has been submitted by press button type “SUBMIT” they will call router POST called add. Make sure we has that route to handle incoming request.
So, we need to add some code to the app.js right ? The code is for the new route we want
If we work with routing, we can just use a get method to go to the that route with passing the link ‘/add’ then like we did for home page, we just render the add.ejs file by just typing add, no need .ejs anymore.
Then if we want to receive the client input form, we can add more route but for now we create POST route, and then we can do destructure the body, if you console.log(req.body) you will see whole the client input (this is work because we install the body-parser), in other way to get the body we can use the way we access the property of object, like this
const title = req.body.title;
const country = req.body.country;
Work as same as destructure
const { title, country } = req.body;
What is desctructure ? Find out ! Before continue.
Nah, we have done with the app.js file, then the add.ejs, but we need to give the link to the add in home page, so just open the index.ejs and add the below code under the table and inside of div class container.
<a href="/add" class="btn btn-primary">Add</a>
Now, we call again the server by type in the terminal
node app.js
Can you try to add some data ? Let me know if you have some problems. Your final code for this step should look like this
views/add.ejs
views/index.ejs
app.js
data
--series.json
node_modules
--blabla
views
--add.ejs
--index.ejs
app.js
package-lock.json
package.json
If your app doesn’t work, just type in the comment what’s your problems I hope I can help you.
How to do Edit
Now, we will go through to do how to Edit our data, and how to do that ?
Logically, we need to choose one data what we want to edit right ? And that’s why we including the id, so we can choose by id not by name (because id is unique and the name can be same each other). After we got the data we choose, we will show the existing data, why ? Because we editing not adding.
We will make new route and new page for edit and also button for edit in each data, so what we do now ? Yeah you are right, create a file called edit.ejs in the views folder and make new route get and post at app.js. What’s code look like ? Here we go now…
First we need to provide the route
You see /edit/:id ? Why we use :id ? With this colon, they will automatically registering the id (name we gave, you can give it another you want) as a parameter, and we also can get the parameter by req.params.id. Then we need to find the data which contain the same ID what we want to choose, then we rendering the edit page with passing the data.
After that, create a file called edit.ejs and copy paste from the add.ejs
The action should be /edit/<%=data.ID%> (you need to pass the id), and change the placeholder to value like this
value="<%= data.Title %>"
And give this to inside of options
<%= data.Country == "Indonesia" ? "selected" : "" %>
<%= data.Country == "Japan" ? "selected" : "" %>
<%= data.Country == "Korea" ? "selected" : "" %>
Why ? This is the feature of EJS you can do that logic, the value came from the data.Title and if the Country if Indonesia that option will has a selected, and it’s also work for Japan and Korea right ? Because just one country we have.
You should learn about Ternary in JavaScript
Then you need to open up the index.ejs, and add more field to your table, you must to add this below code inside of <thead></thead> under the Country
<th scope="col">Action</th>
And then add this code in the <tbody></tbody>
<td> <a href="/edit/<%= d.ID %>" style="color: white"> <button type="button" class="btn btn-success"> Edit </button> </a></td>
Why I use button ? I need to make this anchor looks like button, then you will see the href is /edit/<%= d.ID %> this is the EJS templates can do, they can passing the ID. So, if we click One Piece you know that One Piece ID is 1, so you will redirected to the http://localhost:3000/edit/1 and if you click Naruto, you will go to http://localhost:3000/edit/2 . This is awesome right ?
So, what we will doing now ? Of course we will make the POST route, not for add new data but for update existing data.
The logic is same, you will see that we need to get the data by id first then change the value and finally we save that.
Now, try to edit some values. And this is our code now
views/edit.ejs
views/index.ejs
app.js
How to do Delete
Now, we will going to do delete. And we must pick one between GET or POST, so what we must to choose ? Should we create a route with GET or with POST ?
POST is used when we want to send data to the back end, and GET is the opposite (back end will give something to us) and this one (delete) is so confusing to me, what should I do ? I need to send data to back end which one the data I want to remove and in other side we are not “really” send some data.
I try to find out, and I got some insight, instead I send something to back end with POST why not to just give a parameter and still use GET method ?
Okay we got the answer, so we need to create route or button for delete first ? Hahaha it’s just piece of cake for give a delete button right ? Do your own haha
We add onclick confirm to this because we don’t want to auto delete the data when user is accidentaly click the delete button, so we need to ask the user for surely delete this one or not
And we add route
And if you try to delete the data you will get this error
TypeError: Assignment to constant variable.
And we must to change const variable to let.
const readJson = fs.readFileSync('./data/series.json');const data = JSON.parse(readJson);
to
const readJson = fs.readFileSync('./data/series.json');let data = JSON.parse(readJson);
Remember, after we change the file we need to ctrl + c to stop the server and run again with node app.js
How to do Filter
This is the last thing that we will do, that is a filter. So what will we do is create the form first right, and we will modify the index.ejs because we will put our filter in the data table.
You need to add this code first to index.ejs
Why we need a action=”/” ? because our route is home (localhost:3000/) right, and then why we use GET method instead of using POST method ?
If we use POST we will not get the query url and we can’t save what people try to search, so we do with GET and then the route will give use a query.
<input type="text" name="filter" class="form-control" placeholder="Search..." value="<%= filter ? filter : '' %>">
For the example, we want to search “Naruto” and then we will get the query url like this localhost:3000/?filter=”Naruto”. Depends on what will you give the name of your input, we use this one name=”filter”. Try to change your name of the input tag, and see what happen.
And give your button to type submit. That’s important!
Now, we gonna change our route ‘/’ in app.js.
We can get our query from req.query, it’s same things like we get from req.params.
Now, we will use the logic to do filter. You need to know why I use that logic. This is important why we need to have algorithms, so we can do our own logic.
Now, our tutorial has done guys. I am so sorry if this tutorial is not complex or not enough yet but maybe this tutorial can give you some kind of knowledge about fundamental web development so you can learn more more and more.
Thank you very much!