Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Programming

    22. Long Polling Chat, POST Reading. Pt 1.

    Beginners

    Web Development Contract: Talent Agreement Essentials | Things to Include and Avoid

    Beginners

    Data Science Life Cycle Overview

    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
    Friday, November 28
    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 / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 11: Echo Server
    Node.js

    Node.js Lesson 11: Echo Server

    Mohammad Shad MirzaBy Mohammad Shad MirzaNovember 26, 2020Updated:January 5, 2021No Comments8 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 11: Echo Server
    Node.js Lesson 11: Echo Server
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Node.js Lesson 11: Echo Server
    Node.js Lesson 11: Echo Server

    Hello everyone, today we are going to learn about Echo Servers. We will go through what are they and how to build them. We will also use this little project to learn about the status code and header of an HTTP request. Let’s start.

    What is the Echo Server

    The echo is a reflection of the sounds. Similarly, Echo Server is something that reflects the sent message to the client. If we send a message saying “Soshace”, we will receive the same message, just like an echo.

    GET request: http://localhost:3000/echo?message=Soshace
    response: "Soshace"

    In the above example, the client is sending a message to the server. The server then receives the message and sends the same message back to the client, hence the name “echo”. We can use this type of Echo Server to check if our application is working properly.

    Now, when you have a clear idea of what is an Echo Server is, let’s try to create one ourselves.

    How to create Echo Server

    Echo Servers are fairly simple to make. This involves 3 easy steps:

    1. Create a Server
    2. Accept the Message
    3. Return the message to the Client.

    Step 1: Create a Server

    In the first step, we will add a boilerplate to create the server and listen to a certain port address. It’s very similar to what we have been doing so far.

    const http = require('http');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        // add code her
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    Step 2: Accept the Message

    The req parameter has a bunch of properties that we can use to inspect the type and other info of the request.

    Let’s inspect the method and URL of the request.

    const http = require('http');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        console.log("Method and URL", req.method, req.url);
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    We have created a server, now we just have to make a request. Go to the browser and visit this link:

    http://localhost:3000/echo?message=Soshace

    It will log the method as GET and also the URL that we passed in the browser. But the browser will not return anything. We have not added any code to tell the browser what to do when we receive a request, so it will simply wait and do nothing.

    The state where we don’t receive anything can be confusing when we have added code to send back a response but received nothing. We might think that connection has not been established yet. As a workaround, we will return the message if the url has a message property and the page url is correct. Otherwise, we will simply return a 404 error with the message “Page not found”. This way, we can be assured that our connection is established but something is wrong with the request we made.

    Read More:  Vagrant Tutorial

    So, let’s add code to accept and parse the message now.

    const http = require('http');
    const url = require('url');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const parsedURL = url.parse(req.url);
        console.log('parsedURL', parsedURL);
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    Here, we are using the URL module to parse the requested URL. Right now, we are getting the URL as a string but we need more control to be able to access the message query. Hopefully, there is a simple solution.

    Just pass true in the second argument to url.parse() and it will parse the URL as an object. We can then use it as an object to get the desired properties. Let’s see how:

    const http = require('http');
    const url = require('url');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const parsedURL = url.parse(req.url, true);
        console.log(parsedURL.pathname, parsedURL.query);
        // logs "/echo", { message: "Soshace"}
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    We have the query parameter which can be used to get the message property. Let’s move on to the last step and return the message.

    Step 3: Return the Message to Client

    We are going to check if the URL has a query property with a message and the pathname is also correct. If yes, we will return the message.

    const http = require('http');
    const url = require('url');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const parsedURL = url.parse(req.url, true);
        if (parsedURL.pathname == '/echo' && parsedURL.query.message) {
            res.end(parsedURL.query.message);
        } else {
            res.end("Page not found");
        }
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    We also added an else block that will take care of requests when the page url is wrong or the message query parameter is not present. You can check this by entering the wrong url or simply not pass any message.

    We finally created an echo server that accepts the message and returns them to the client. But we are not done yet. The response has a header and status code that provides info about the response. For example, a page not found response has a status code 404 and a successful request has a status code 200. We have to take care of that too.

    Adding Status Code

    A server categorizes the response with the help of status codes. Successful request completion is referred to as status code 200 and a failure at the server-side is often seen as status code 500. These status codes tell us about what happened on the server when we made a request and in turn help us debug when we encounter any issue. There are mainly five types of status code that the server issues in response to a request.

    • Informational Response: the request was received, continuing process. Follows pattern 1xx. Example: 100
    • Successful: the request was successfully received, understood, and accepted. Starts with 2 and follows pattern 2xx. Example: 200, 203, 206.
    • Redirection: further action needs to be taken on the user side to complete the request. Follows pattern 3xx. Example: 300, 303.
    • Client Error: the request contains bad syntax or input that the user might have entered and cannot be fulfilled. Follows pattern 4xx. Example: 400, 404.
    • Server Error: the server failed to fulfill a valid request. Follows pattern 5xx. Example: 500, 503.

    Refer to this sheet for detailed info on all the available status codes.

    We will add 2 of these to our server for success and the wrong path.

    const http = require('http');
    const url = require('url');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const parsedURL = url.parse(req.url, true);
        if (parsedURL.pathname == '/echo' && parsedURL.query.message) {
            res.statusCode = 200; // when request is successful
            res.end(parsedURL.query.message);
        } else {
            res.statusCode = 404; // when request is failed due to wrong url
            res.end("Page not found");
        }
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    I think it looks good enough. Let’s take care of the header now.

    Read More:  Programming Patterns. Introduction

    Add Header

    Headers are part of every HTTP request and response. They represent metadata about the request/response. They are very helpful when we run into issues and have to find what caused them. They contain information like connection type, cors allowance, authorization, content type, etc.

    We can make the request cache-free by adding a cache-control header.

    const http = require('http');
    const url = require('url');
    const port = 1337;
    const host = 'localhost';
    
    const server = http.createServer(function (req, res) {
        const parsedURL = url.parse(req.url, true);
        if (parsedURL.pathname == '/echo' && parsedURL.query.message) {
            res.statusCode = 200;
            res.setHeader('Cache-control', 'no-cache');
            res.end(parsedURL.query.message);
        } else {
            res.statusCode = 404;
            res.end("Page not found");
        }
    });
    
    server.listen(port, host, function () {
        console.log('Web server is running on port 1337');
    });

    Let’s learn about what other header options are available.

    Authorization

    Carries credentials containing the authentication information of the client for the resource being requested.

    WWW-Authenticate

    This is sent by the server if it needs a form of authentication before it can respond with the actual resource being requested. Often sent along with a response code of 401, which means ‘unauthorized’.

    Accept-Charset

    This tells the server about which character sets are acceptable by the client. We set them while making a request.

    Content-Type

    Indicates the media type (text/html or text/JSON) of the response sent to the client by the server. This helps in parsing the response at the client-side.

    Cache-Control

    This is the cache policy defined by the server for this response, a cached response can be stored by the client and re-used till the time defined by the Cache-Control header. That’s it for this article, I hope you learned something. We will see you in the next article. You can find this lesson’s coding in our repository.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    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
    Programming September 12, 2016

    С днем программиста!

    Read More:  The Ultimate Guide to Drag and Drop Image Uploading with Pure JavaScript

    Introduction to GitHub Desktop: A GUI Enhancement to a CLI Approach

    November 5, 2019

    How to pay your foreign remote workers?

    October 9, 2018

    14. Уроки Node.js. Отладка скриптов. Часть 1.

    September 28, 2016

    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

    Building a Telegram Bot with Node.js

    JavaScript December 6, 2019

    5 Critical Tips for Designing Your First Website

    Beginners July 5, 2019

    Create a Simple POS with React, Node and MongoDB #0: Initial Setup Frontend and Backend

    JavaScript January 7, 2020

    Setting Up Automated Semantic Versioning For Your NodeJS Project

    JavaScript August 8, 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
    Beginners

    What Is Responsive Web Design?

    Programming

    GraphQL

    Development

    Enhancing Code Quality: Best Practices for Software Development

    Most Popular

    Why Fastify is a better Nodejs framework for your next project compared to Express

    Node.js

    Conducting Effective Post-Project Evaluations: A Guide

    JavaScript

    Server-Side Rendering with Vue.js and Nuxt.js

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

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