Node.js Archives - SoftUni Global https://softuni.org/tag/node-js/ Learn Programming and Start a Developer Job Thu, 30 Jun 2022 12:06:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.3 https://softuni.org/wp-content/uploads/2022/04/cropped-SoftUni-Global-Logo-Square-notext-32x32.png Node.js Archives - SoftUni Global https://softuni.org/tag/node-js/ 32 32 URL Shortener Project – Adding Views, Layout + CSS Styling [Part 2] https://softuni.org/project-tutorials/url-shortener-project-adding-views-layout-css-styling/ https://softuni.org/project-tutorials/url-shortener-project-adding-views-layout-css-styling/#respond Fri, 18 Feb 2022 06:00:00 +0000 https://softuni.org/?p=12378 In our second part of the URL Shortener series, we continue with developing our project. We will create all the views, CSS, and layout page for the project.

The post URL Shortener Project – Adding Views, Layout + CSS Styling [Part 2] appeared first on SoftUni Global.

]]>

In the second part of the tutorial, we will create the user interface for our web application. This will include all the views, CSS, and the layout page. If you haven’t read our previous blog post, where we created our project, you can do it from here.

We start with building the layout page. It allows us to define a common site template that can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.

  • Inside the views folder, we create a layout.pug.

layout.pug

				
					<!DOCTYPE html>
html(lang='en')
  head
    block head
    link(rel='stylesheet', href='/styles.css')
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  body
    header
      a(href='/') Home
      span  | 
      a(href='/urls') Short URLs
      span  | 
      a(href='/add-url') Add URL

    main
      block content
    
    footer
      div © 2022 - URL Shortener
				
			
  • In the head section, we import the .css file that will include our styling. We will create it later inside the public folder.
  • For the body part, we have a header with the navigation of our application. Each anchor tag will lead us to another route.
  • In the main block is the block content that every time will re-render differently depending on our route.
  • We will create a styles.css in our public folder that we made in our previous part.
 

styles.css

				
					body {
  font-family: Arial, Helvetica, sans-serif;
}

header, footer {
  background:rgb(212, 233, 164);
  padding: 8px;
  border-radius: 3px; 
}

footer {
  margin-top: 15px;
}

main {
  margin-left: 10px;
}


table {
  width: 100%;
  border-collapse: collapse;
  background-color: #f5fff5;
}

table th, table td {
  border: 1px solid #ddd;
}

table th {
  padding: 12px 8px;
  text-align: left;
  background-color: rgb(107, 182, 109);
  color: white;    
}

table td {
  padding: 8px;
  overflow-wrap: anywhere;
}

table tr:nth-child(even) {
  background-color: #dff0de;
}

table tr:hover {
  background-color: rgb(198, 207, 180);
}


form table {
  width: 100%;
  max-width: 600px;
}

form table td:nth-child(1) {
  width: 10%;
  white-space: nowrap;
}

main form input {
  width: 100%;
  min-width: 100px;
  box-sizing: border-box;
}

				
			
  • If we want to add more pages, we need to set up the routes in our controller. As we did in the previous part, we create different functions for each  route. In the mvc-controller.js, we  will expand the functionality with new functions.

mvc-controller.js

				
					function setup(app, data) {
  app.get('/', function(req, res) {
        //  Same as before
  });

  app.get('/urls', function(req, res) {
    let model = { urls: data.urls };
    res.render('urls', model);
  });

  app.get('/add-url', function(req, res) {
    let model = { url: "", code: "newCode" };
    res.render('add-url', model);
  });

  app.post('/add-url', function(req, res) {
    res.redirect('/urls');
  });

}

function date2text(inputDate) {
  let date = inputDate.toISOString().split('.')[0];
  date = date.replace('T', ' ');
  return date;
}

module.exports = { setup };
				
			
  • With the first function, we will get the view with all the URLs. It will be the same as the home view functionality.
  • The second function will load the view for the create page. We will access it with the “/add-urlroute.
  • The next third function will have the same route as the previous but with a different type of request. In the app.get(‘/add-url’, … ) we request the view, but with app.post(‘/add-url, …) we will send data to the server. They are on the same route, but we send different types of requests.
  • We will add a helping function data2text() that will be outside of the setup() function. It will help us later.
  • What we need to do next is to create .pug view. First, we will add the urls.pug inside our views folder. We add the following code inside it:

urls.pug

				
					extends layout.pug

block append head
  title='Short URLs'

block content
  h1 Short URLs
  table
    thead
      tr
        th Original URL
        th Short URL
        th Date Created
        th Visits
    tbody
      each url in urls
        tr
          td 
            a(href=`${url.url}` target="_blank") #{url.url}
          td
            a(href=`${url.shortUrl}` target="_blank") #{url.shortUrl}
          td #{url.dateCreated}
          td #{url.visits}
				
			
  • In this view, we will have an HTML table featuring all the records that we request from the server. They are bound to the urls variable. To access each element separately we need to iterate over the collection with a for-each loop. Each row will be with data for a specific record, and every cell with a value for a specific property of the object.

If we start the project and go to the ‘/urlsroute, this will visualize: 

urls-view

  • In next part we will add the add-url.pug view. We add it inside the views folder.

add-url.pug

				
					extends layout.pug

block append head
  title='Add Short URL'

block content
  h1 Add Short URL
  form(method='POST' action='/add-url')
    table
      tr
        td
          label(for='url') URL: 
        td
          input#url(type='text', name='url', value=`${url}`)
      tr
        td
          label(for='code') Short Code: 
        td
          input#code(type='text', name='code', value=`${code}`)
      tr
        td(colspan="2")
          button(type='submit') Create
				
			
  • In this view, we add a form that is with a POST method, and an action points to ‘/add-url‘. To explain what this does, after pressing the submit button, the server will request the app.post(‘/add-url’, …) function that we have typed inside our mvc-controller.  In the next parts, we will add the functionality that saves the record inside the database.
  • Inside the form, we have two input fields. Inside each field, the user will type the values for the URL he needs to create.
  • In the end, it is important for the button to be of type submit. This will submit the form to the server.

If you have done everything correctly, going to the ‘/add-urls‘ route will display you this page:

add-url-view

After completing all the steps, your project will have a user interface that supports different types of screens. If we go to our two new routes ‘/urls‘, and ‘/add-urls‘ you will access the two new pages that we have added. On the ‘/add-urls‘ route, if you submit the form with the required data, you will send a POST request to the server. In the next parts, we will be able to save this information on the server and display it inside the ‘/urlsroute.

Lesson Topics

In this tutorial we cover the following topics:
  • Building the Layout Template in Pug
  • Adding CSS Styles
  • Implementing the “View Short URLs Table”
  • Styling the Table
  • Implementing the “Add URL” Form
  • CSS Styling for Small Screens

Lesson Slides

The post URL Shortener Project – Adding Views, Layout + CSS Styling [Part 2] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/url-shortener-project-adding-views-layout-css-styling/feed/ 0
URL Shortener Project – Creating the App Structure [Part 1] https://softuni.org/project-tutorials/url-shortener-project-creating-the-app-structure/ https://softuni.org/project-tutorials/url-shortener-project-creating-the-app-structure/#respond Thu, 10 Feb 2022 06:00:00 +0000 https://softuni.org/?p=12280 In this article of the Project Tutorial series, we will create a simple URL Shortener, using JavaScript, Node.js, Express.js and Pug

The post URL Shortener Project – Creating the App Structure [Part 1] appeared first on SoftUni Global.

]]>

In this tutorial, we will create our URL Shortener using JavaScript. We will be using Expres.JS for creating the server-side web application and Pug as a template engine. This tutorial will be split into several parts, and in each part, we will further develop our project. In the end, we will have a fully working Multi Page Application (MPA).

After we initialize our project, we need to split our code logic into different folders. We create folders for:

  • data
  • controllers
  • views
  • public

In our main directory we have an index.js file that is automatically generated by repl.it. You don’t need to install manually any libraries because they will be added automatically when you start the project.

First, in our index.js we need to add the following code:

 

index.js

				
					const express = require('express');
const app = express();
app.use(express.static('public'))
app.set('view engine', 'pug');

const data = require("./data/app-data");
data.seedSampleData();

const mvcController = require(
  "./controllers/mvc-controller");
mvcController.setup(app, data);

let port = process.argv[2];
if (!port) port = process.env['PORT'];
if (!port) port = 8080;

app.listen(port, () => {
  console.log(`App started. Listening at http://localhost:${port}`);
})
.on('error', function(err) {
  if (err.errno === 'EADDRINUSE')
    console.error(`Port ${port} busy.`);
  else 
    throw err;
});
				
			
  • In the first row, we import the ExpressJS node module. Then we bind it to a constant and use it to make static our public folder. Doing this will allow us to use the public folder from any part of our application.
  • We will also set our view engine to pug. This will render all .pug files we set as views.
  • We define constant named data and invoke the function. seedSampleData() inside it. We will create them later. Every time our project is started this function will be initialized.
  • Our next task is to tell the index.js that our MVC-controller exists and set up it.
  • We set our virtual port for repl.it to 8080, and tell the program to listen to this port.
  • If there is an error, it will be automatically displayed on the server’s console.

app-data.js

				
					let urls = [];

function seedSampleData() {
  urls.length = 0; // cleanup
  urls.push({
    url: "https://softuni.org",
    shortCode: "su",
    dateCreated: new Date("2022-02-19T16:41:56"),
    visits: 86
  });
  urls.push({
    url: "https://nakov.com",
    shortCode: "nak", 
    dateCreated: new Date("2022-02-17T14:41:33"), 
    visits: 160
  });
}

module.exports = {
  urls,
  seedSampleData
};
				
			
  • In our data folder we create an app-data.js file. In it is we create our seed of data. We add an empty array that we fill with the seedSampleData() function.
  • In our function we have 2 different objects {} that we push into the urls array.
  • This is a temporary solution and in our next parts will be changed with a real database.

mvc-controller.js

				
					function setup(app, data) {
  app.get('/', function(req, res) {
    let visitors = 0;
    for (const url of data.urls) {
      console.log(url);
      visitors += url.visits;
    }
    let model = { urls: data.urls, visitors };
    res.render('home', model);
  });
}

module.exports = { setup };
				
			
  • Inside our controller folder we create the  mvc-controller.js file. Inside it, we add the function setup() that receives the app and data
  • When our server recieves a GET request with a URL that equals ‘/’, it will invoke the following function.
  •  We iterate over the collection of data and bind it into the model variable. 
  • Then, we render the following view with the data attached to it. 
  • After we are done, we export the function so that the index.js can run it correctly.

home.pug

				
					h1 URL Shortener
ul
  li Short URLs: <b>#{urls.length}</b>
  li URL visitors: <b>#{visitors}</b>    
				
			
  • Finally, we create our home.pug view inside the views folder. That is the html page that will load when the user goes to the ‘/’ URL, that we defined in our controller.
  • We have an unordered list( ul ), in which we have two rows( li ). The first is for the count of our URLs, and the next is the total sum of all visitors summed from all 2 records.
  • If we want to print the data bound to the variable visitors, we must add hashtag # and braces { } around it so that our compiler knows that this isn’t a regular HTML text.

url-first-part-final-lookAfter completing all the steps you will have a simple working Multi Page Application. If you start your project, you will see that everything that we have done is working correctly. We are using the MVC architecture, and we have split the project into different folders and functions for better understanding. This way  you can clearly see where each part is located. Keep up with our parts and see how our project grows more.

Lesson Topics

In this tutorial we cover the following topics:
  • URL Shortener: App Walkthrough
  • Project Structure
  • Creating the App Structure

Remember that coding is a skill, which should be practiced. To learn to code, you should write code every day for a long time. Watching tutorials is not enough. You should code! 

We would love to hear from you, so leave a comment below saying what topics you would like to see next.

Register now and take your free resources right away! Become a member of the SoftUni Global Community and communicate with other students and mentors and get help for FREE.

After registering, you will get access to thе project code.

Lesson Slides

The post URL Shortener Project – Creating the App Structure [Part 1] appeared first on SoftUni Global.

]]>
https://softuni.org/project-tutorials/url-shortener-project-creating-the-app-structure/feed/ 0