Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Consultation

    Best Service provides for Small Businesses

    Trends

    4 Tech Factors Driving the World Economy of Tomorrow

    CSS

    Sass vs. Less: Which CSS Preprocessor to Choose in 2019?

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Thursday, December 4
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / Express.js Lessons. Logger, Configuration, Templating with EJS. Part 2.
    Programming

    Express.js Lessons. Logger, Configuration, Templating with EJS. Part 2.

    Ivan RastvorovBy Ivan RastvorovDecember 2, 2016Updated:April 5, 2019No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Express.js Lessons. Logger, Configuration, Templating with EJS. Part 2.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    express_2_2

    Favicon is the connect  of Middleware that checks whether the url has a view of favicon.ico; if the answer is ‘yes’, it reads favicon  and outputs, otherwise it transfers control further. The logger outputs a record what kind of a request we’ve received. For example, if we launch the app now, the logger will output something, when we follow:

    http://localhost:3000/

    That is a standard  Httplog requests, while dev is a logging format. There are also other formats – for example,  default (let us add the respective record in app.js):

    app.use(express.favicon()); // /favicon.ico
    if (app.get('env') == 'development') {
      app.use(express.logger('dev'));
    } else {
      app.use(express.logger('default'));
    }

    Various formats can be found in the connect supporting materials. Here you will find different variants of built-in formats. There is one more amazing setting for adding a record into log. It often writes into log upon a request ending. But we can indicate immediate: true, and it will write into log in the very beginning.

    But what is the difference, if we talk about our code? If we’ve got the option immediate, a logger will write into log, and further, through next, transfer control over the next  Middleware. It is the most likely control flow. But we’ve got a different thing by default – the logger rewrites res.end to its function that writes into log upon being called. So, it turns out, if we log this way, without the flag  immediate, then if log doesn’t contain anything, it doesn’t mean there was no request.

    Keep that thing in mind. It may happen that the request really existed, but hung up because NODE didn’t handle it. Respectively, everything will go to log only upon the request end.

    BodyParser deals with reading the forms sent via the post method, reads JSON data sent using this method. It means, the request body gets parsed. The data transferred through post, as well as similar methods get read using flows. This is an asynchronous action. BodyParser deals with all these things, absolutely reads post. And if it’s  JSON, itparse it, and the data becomes accessible in req.body:

    app.use(express.bodyParser());  // req.body....

    Once it has completely read the post, this Middleware transfers control further through next.

    CookieParser parses as well, but cookies instead of the body. So, there may be headers like these: req.headers. It divides them and makes the respective properties of the object cookies:

    app.use(express.cookieParser('your secret here')); // req.cookies

    Here we can specify an optional key the cookies will be signed with. Right now we don’t need this record and will talk about it later.

    Read More:  How To Secure Python Web App Using Bandit

    Router allows us to talk seamlessly about what requests will be there and how they will be handled. For instance, let us add the following code:

    app.use(app.router);
    
    app.get('/', function(req, res, next) {
      res.end("Test")
    });

    Respectively, instead of get there may be post, put, del, etc. Moreover, this Middleware contains a number of extra options (you may transfer parameters, etc.).

    The last Middleware is static. Generally, static gets displayed by other servers, not Node.js, but it can do it, too. So, if no Middleware handles the request here, the control gets delivered to Middleware static.

    app.use(express.static(path.join(__dirname, 'public')));
    

    It checks, whether the  public directory has got the respective file. Let us change the names of public directories a little bit(stylesheets-> css,  javascript->js). Launch it, everything works!

    App.js looks like that, check it out:

    var express = require('express');
    var http = require('http');
    var path = require('path');
    var config = require('config');
    var log = require('libs/log')(module);
    
    
    var app = express();
    app.set('views', __dirname + '/templates');
    app.set('view engine', 'ejs');
    
    app.use(express.favicon()); // /favicon.ico
    if (app.get('env') == 'development') {
      app.use(express.logger('dev'));
    } else {
      app.use(express.logger('default'));
    }
    
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    
    app.use(app.router);
    
    app.get('/', function(req, res, next) {
      res.end("Test")
    });
    
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use(function(err, req, res, next) {
      // NODE_ENV = 'production'
      if (app.get('env') == 'development') {
        var errorHandler = express.errorHandler();
        errorHandler(err, req, res, next);
      } else {
        res.send(500);
      }
    });
    
    // var routes = require('./routes');
    // var user = require('./routes/user');
    
    // // all environments
    
    // app.get('/', routes.index);
    // app.get('/users', user.list);
    
    
    http.createServer(app).listen(config.get('port'), function(){
      log.info('Express server listening on port ' + config.get('port'));
    });
    

    Eventually, instead of such a simple message, let us output a common HTML page. For that reason, I will create a new file in the template directory and call it index.ejs. The file extension is  ejs, since a ejs-related template is usually created this way. The template itself is an HTML, and you can use special extra dividers in order to insert the code or variables, for example:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Hello, World!</title>
    </head>
    <body>
    <section class="container">
    
      <h1>Hello, World!</h1>
    
      <%=body%>
      <%-body%>
    
    </section>
    </body>
    </html>

    We can find more detailed information in our technical materials. If we want some special example, the code may be:

    <% if (user) { %> 
       <h2><%= user.name %></h2>   
    <% } %> 
    

    <% if (user) { means inserting the JavaScript code, which means the operator if will be executed, while %= means adding the variable values.  <%-body%> also means inserting of a variable. But if there is some kind of an unsafe text in the  body  (for example, <script>), in this case – <%-body%> – it will be inserted the way it is, and if there is <%=body%>, it will be changed with safe symbols.

    Read More:  Amazon S3 Cloud Storage Proxying Through NodeJS from Angular Frontend Securely

    Let us show the example of:

     <%=body%>
      <%-body%>

    Of course, we need to transfer a variable to the template. But how can we do it?  The principle is very simple, just write in app.js:

    app.get('/', function(req, res, next) {
      res.render("index", {
        body: '<b>Hello</b>'
      });
    });

    Check it. Enter

    http://localhost:3000/

    html

    As you can see, the first body has been inserted marked with =, while the second – with -.

    We’ve got the simplest Express website, with the output into the variable template. In our next article we will work a bit more with templates, front-end part, and then will move to the data.

    The lesson code can be found here.
    staytuned2

    The materials for this article were borrowed from the following screencast.

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ivan Rastvorov
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript July 29, 2020

    React Lesson 15: Checking Homework progress from Lesson 14

    Today, we are going to cover homework from Lesson 14 and add comment API to load comments.

    8 Best Bootstrap UI Kits – World’s Most Popular & Free UI Frameworks

    June 24, 2019

    Уроки React. Урок 12.

    November 1, 2016

    Bootstrap: TOP 5 Free Bootstrap Editors & Tools

    May 28, 2019

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Everything You Wanted to Know about the UX Research Methods

    Beginners September 4, 2019

    Effective Strategies for Managing Project Dependencies

    JavaScript November 24, 2024

    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC

    Node.js September 30, 2020

    TOP Most In-Demand IT Certifications 2020

    Beginners January 1, 2020

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Node.js

    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC

    JavaScript

    How to Creact a React Component Library – Using a Modal Example

    Beginners

    The Concept of Scope in JavaScript

    Most Popular

    How to Prepare for Your First Coding Job Interview?

    Interview

    16. Уроки Node.js. Событийный цикл, библиотека libUV. Часть 1.

    Programming

    Create simple POS with React.js, Node.js, and MongoDB #16: Order Screen

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.