Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Entrepreneurship

    Essential Strategies for Building a Robust Entrepreneurial Network

    JavaScript

    Top AngularJS interview questions

    JavaScript

    Building a Simple CLI Youtube Video Downloader in NodeJS

    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
    Wednesday, September 10
    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. Express: Basics and Middleware. Part 2.
    Programming

    Express.js Lessons. Express: Basics and Middleware. Part 2.

    Ivan RastvorovBy Ivan RastvorovNovember 24, 2016Updated:April 5, 2019No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Express.js Lessons. Express: Basics and Middleware. Part 2.
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    expess_1_2

    Hey, guys! Let’s continue our lesson about Express basics and Middleware.

    The result is (add to app.js):

    app.use(function(req, res, next) {
      if (req.url == '/') {
        res.end("Hello");
      } else {
        next();
      }
    });

    The function next serves to deliver control further down the chain to the next Middleware, or to the next function that is announced through app.use. The second Middleware can also check something and transfer control further:

    // Middleware
    app.use(function(req, res, next) {
      if (req.url == '/') {
        res.end("Hello");
      } else {
        next();
      }
    });
    
    app.use(function(req, res, next) {
      if (req.url == '/test') {
        res.end("Test");
      } else {
        next();
      }
    });

    Launch it in a following way and see what we’ve got.

    http://localhost:3000/

    http://localhost:3000/test

    Everything works.

    And what will happen, if we follow a page that does not exist?

    http://localhost:3000/nopage

    The integrated Express handler has worked. If there is no  Middleware , next has been called, and the next Middleware does not exist, Express outputs a ‘Not Found’ page by default. In order to influence it somehow, let us create one more Middleware to receive req and res, the one that will always be the last in this chain:

    app.use(function(req, res) {
      res.send(404, "Page Not Found Sorry");
    });

    Launch it. Note, there is a correct 404 status in console. Here we’ve just used the method res.send. Standard req and res elements lack it, but you can find it in  Express, for the reason it expands req  and res  objects prior to calling a Middleware chain, expands objects through inheriting and adds some of its methods to them. These methods can be found at expressjs.com. There you will find API Reference that includes a lot of things – in particular, we need Response and a send method. Its simple form is: res.send(hello world); – to send a line, but there are some more challenging and interesting variants:

    res.send(new Buffer('whoop'));
    res.send({ some: 'json' });
    res.send('<p>some html</p>');
    res.send(404, 'Sorry, we cannot find that!');
    res.send(500, { error: 'something blew up' });
    res.send(200);

    Send can send various things: Buffer, json, text; and if the first argument is a number, it puts a respective status, too. So, this method is quite versatile and handy.

    Read More:  21. Node.js Lessons. Writable Response Stream (res), Pipe Method. Pt.2

    But what will happen, if we’ve got an error somewhere? Let us create a special Middleware, call it error, and there will actually be an error:

    app.use(function(req, res, next) {
      if (req.url == '/error') {
        BLABLA()
      } else {
        next();
      }
    });

    Go to :

    http://localhost:3000/error

    The built-in Express error handler has worked. It works only when  Middleware has throw.

    app.use(function(req, res, next) {
      if (req.url == '/error') {
        throw new Error ('......')
      } else {
        next();
      }
    });

    Of course, it won’t work, if this throw is wrapped into setTimeout. That’s what the principle of JavaScript is.

    Now let us deal with the correct handling of all errors – the ones that occur in the average process of work of our website. Let us pretend, a user has followed a url that is forbidden for entering. In this case we can either notify him immediately (res.send(401)), or sometimes it is even more convenient to deliver the error further down the chain. That’s how it looks like (let us change our previous function):

    app.use(function(req, res, next) {
      if (req.url == '/forbidden') {
        next(new Error("wops, denied"));
      } else {
        next();
      }
    });

    If there is some argument inside next , Express knows it is an error and delivers it to an error handler. By default, a handler of this kind, as we’ve already seen, outputs a stack, which is inappropriate in real situations. So, we can create our own handler. It is programmed in the same way as Middleware, while app.use is just a function with 4 instead of 3 elements:

    app.use(function(err, req, res, next) {
    

    In JavaScript every function has a length property that contains a number of arguments in its declaration, that’s why when seeing a function with 4 arguments, Express is able to understand it is an error handler. Respectively, if an error occurs – either  throw or  next has been called with an argument – the control gets immediately transferred to

    app.use(function(err, req, res, next) {
    
    }

    Here we can already output an error: in a development case it will be stack, and in real life it will be an error code, template, etc.

    Read More:  Top 11 SQL Interview Questions | Theory and Practice for 2019

    How can we know whether the script includes a development case or a real launch? For that reason, we’ve got a special value that can be received using app.get('env'). If a special  NODE_ENV environment variable is not specified, this thing will be development. But if it does include that variable, it will be equal to the value of this variable:

    app.use(function(err, req, res, next) {  
      // NODE_ENV = 'production'  
      if (app.get('env') == 'development') { 
    

    In real-life launch it has a value production.  Respectively, if it is development, let us output the error beautifully. For that reason, we’ve got a special built-in Middleware – express.errorHandler. Let us take it out of a generated template and insert here:

    app.use(function(err, req, res, next) {  
      // NODE_ENV = 'production'  
      if (app.get('env') == 'development') {  
        app.use (express.errorHandler());  
    }
    }); 
    

    What kind of thing is that? Let us take a precise look at our Express sources. What Express exports does not include errorHandler. To find it, we should look deeper in what’s going on here, in particular, in our loop:

    for (var key in connect.middleware) {
      Object.defineProperty(
          exports
        , key
        , Object.getOwnPropertyDescriptor(connect.middleware, key));
    }
    

    Еxpress is a framework created around another framework called  connect. (starting from the version Express 4 it is not so anymore, but our lesson is built on the version Express 3). It contains various Middleware that get included into Express this way by default. Middleware can be found in

    node modules→connect→ lib→middleware →errorHandler.

    Now let us create errorHandler and deliver a request in an explicit view to it, as the previous code, unfortunately, won’t work:

    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);
      }
    });
    

    Check it. We’ve got development, so the respective branch if has worked.

    In our upcoming articles we will continue working with  Express, analyze built-in  Middlewares and output a normal html page.

    The lesson code can be found here.

    keep-calm-and-express-yourself-445

    The materials for this article have been 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 24, 2020

    Ways to optimize React applications

    Developing applications that are fast and efficient has always been the goal of every developer out there. Most of the job when working towards achieving the goals above gets done by frameworks and libraries like React, Angular, etc. A library like React is fast, and in most cases, you won’t need to apply optimization techniques to make your application faster or more efficient.

    Mapping the World: Creating Beautiful Maps and Populating them with Data using D3.js 

    January 21, 2020

    Web development trends 2018-2019

    October 21, 2018

    Enhancing Software Development: The Crucial Role of Version Control

    December 9, 2024

    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

    Effective Strategies for Targeting B2B Lead Generation Audiences

    B2B Leads December 19, 2024

    How to Architect a Node.Js Project from Ground Up?

    JavaScript December 19, 2019

    Setting CSS Styles with JavaScript

    CSS December 25, 2019

    Overview of Basic Data Structures: How to Organize Data the Efficient Way

    Beginners August 13, 2019

    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
    Trends

    4 Tech Factors Driving the World Economy of Tomorrow

    JavaScript

    Streamlining Resource Allocation for Enhanced Project Success

    Express.js

    Mastering JavaScript Proxies: Practical Use Cases and Real-World Applications

    Most Popular

    Top Influencer Marketing Platforms to Explore in 2025

    Influencer & Community

    Three Essential Rules for Architecting iOS Unit Tests in 2020

    Beginners

    Partnerships with Conferences: Announcement for 2019-2020

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

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