Introduction
Academic / school year is almost over, and while some of you may have a few more subjects to finish, summer vacation is starting. Having fun and getting your mind off the school is expected, but we believe that you should spend, at least a part of, your free time expanding your knowledge. This is why we’re writing this article, to give you an example of a small summer project for you to work on and expand it.
In this example, we’ll be making a simple application with NodeJS and Express. So we will be showing:
- Html
- Css
- JavaScript
- JSON
So, let’s start.
Concepts
Let’s first explain some basic concepts that will be shown here.
JavaScript
JavaScript is a scripting programming language that was mostly used for front-end in web development, and it still is of course. But lately, it’s becoming more and more popular as a server-side language through NodeJS. There’s a lot of lessons on W3Schools, and other sites, so you can explore more, but for now, this is enough.
JSON
JSON stands for JavaScript Object Notation and is a file format that is used to transfer data that is language agnostic. JSON basically became a replacement for XML because it’s easier to read and to work with.
JSON consists of “name”:value pairs that are stored in objects and arrays. { } brackets contain objects and [ ] brackets contain arrays. So a simple JSON object would look like this:
You can put JSON objects inside an object, like this:
NodeJS
We have a separate article called Introduction to NodeJS which you should read before continuing, but in short, NodeJS is a JavaScript runtime engine that let’s you use JavaScript for server-side scripting. So of course, you need to install NodeJS for this project.
You can create a NodeJS project by opening VS Code and typing npm init in VS Code’s terminal. You can open the terminal by expanding the bottom part of VS code up or by pressing the combination of CTRL +¸ or View -> Terminal.
If by any chance you don’t know what VS Code is, it stands for Visual Studio Code and it is one of the best free code editors that can be expanded with extensions.
Now, let’s start with our example.
Simple nodeJS server rendering HTML
We are going to make a simple NodeJS server that will server static files (our html and css files). We are going to make it with Node and http and fs packages.
First, if you didn’t read and follow our introduction to NodeJS article, you need to create a package.json file with:
- npm init -y
This is our app.js file that creates and runs our server.
You can see that we declare our constants to work with and create a function with request and respones as parameters. Inside the function, we write a header with our content type which is text/html because we are going to render a html file.
Then we’re reading index.html file and creating a function that will render our index.html file, if it exists of course. If it doesn’t exist, we’ll be showing a 404 not found error.
And in the end, we are making our server listen on localhost, on port 3000.
Now, in our index.html, we have a simple list of the tasks we’ve done, here’s the code:
Structure and other packages
Now that we are rendering a html page, anything you change in index.html will be changed on your page, you can now add other pages, CSS and other things. However, anything you change in you app.js file won’t be submitted until you restart your server. But, there is a simple Node package that can solve that and it’s called NODEMON. You can get it with:
- npm install -D nodemon
This will automatically create your package.json file that will contain a JSON record of your packages. Also, node_packages folder will be created that will contain actual packages and their code.
Now we can run our app with nodemon:
- nodemon app.js
Any changes to your app.js will trigger a restart so you don’t have to do it manually.
Further development
So, now you can run your index.html and write JS and CSS using script and style tags. But you can’t add external js or css files. You can’t go to other html files via links a tag like you would in PHP.
For that, you’d usually use Express package and that’s what we’re gonna do. We created a new folder called „public“ that contains 4 other folders „css, js, img and views“ which will contain our css, js, html files and images.
We’re also gonna install express and ejs as well as change the project layout quite a bit. We’ll also change app.js.
First off, we’ll create our directories as above, then we’ll create „main.css“ and place it in our css directory, following that, we’ll move our index.html to views directory. So, it should look like this:
Express and Ejs
We don’t have all our files yet so some folders are empty.
We have to install express package in order to use it. Like this:
- npm install express
And let’s now modify our app.js file to use express.
This code has now loaded our static files like html, css, javascript and images. If you run your code now, you’d see the contents od your index.html page so be sure to write some html code there or you’ll get a white screen.
Using EJS
Now we’re gonna use our ejs package. For those wondering, EJS stands for Embeded JavaScript, and it is really just a template engine that let’s you dynamically generate HTML. We aren’t using EJS’s capabilities in this example, but you can do some research on your own.
Firstly we need to refactor our html pages to ejs (just change .html to .ejs). Then we set our views and refactor our app.get function (inside app.js file). Just add this code at the end of your app.js, like this.
Now let’s create a second page called about.ejs where you can just write some simple text. The point is to load it with the url suffix of /about. So, when you have your about.ejs (in views folder) ready, add this to your app.js.
and check your localhost:3000/about.
Now that that is set up. We can use our static files, let’s add css to our index.ejs in head tag.
Adding css, other pages and more
You’ll need to create main.css file in your css directory and put some commands in.
By now, you probably noticed that you just add stuff and they are show on the page, no need for refreshing and restarting thanks to nodemon.
The last thing you’d need to have is a navigation. So in index.ejs you add
and in your body tag, and in about page, you add
We’re adding just the “/” in the path because we marked our index file as ” in app.js.
This is a very simple example that you can expand with additional css, ejs pages, javascript scripts and more.
Now that we finished this, let’s do another simple example and create a simple API, that will return JSON data, with express.
Making a simple API with NodeJS and Express
First off, let’s see our JSON file. Our JSON, we have user objects that consist of data like name, last name, age and car, car is an object that consists of data like manufacturer, model and power in KW.
And here’s the response on our localhost when we run the script. Let’s see how we did it.
Code
Server.js is your main JavaScript file, as app.js was in our previous example. An here is the code that is in our server.js. So, we’re using express again and the code is pretty much similar to the previous example, but this time we are not serving static files (aside from cars.json). You can try to send a GET request to your API’s address and get the data.
To clarify things a bit, function(req, res) is a function that is ran every time a the url receives a request, and it sends the response back, response being our cars.json.
While you have your API running, you can try to send a GET request to it with Postman or Insomnia. Postman is basically a collaboration platform for API development and it enables you to send requests and test your API’s.
To better understand API’s and to make better API’s, there’s a Api specification called OpenAPI which provide a set of rules to describe API’s and document them.
Conclusion
We set up a baseline NodeJS projects for you to clone and expand on. We hope that you will learn something from this and improve your skill set since NodeJS is a growing technology which takes up more and more market share for web applications.