Search

What Is the Purpose of AJAX in JavaScript.

Asynchronous JavaScript And Xml (AJAX) is the best solution, whenever you want to update your webpages asynchronously by exchanging the data to/from the server . It simply means that without reloading the complete webpage for your application we can update parts of the web application dynamically and asynchronously without sending the request back to the server. AJAX is the combination of XMLHttpRequest Object, JavaScript and HTML DOM (Document Object Model). As we already know, JavaScript allows us to add enhanced functionality and helps web pages to interact with the clients asynchronously. JavaScript mainly runs on the client side, which is known as the browser. Whenever a JavaScript function sends the request asynchronously from the client to the server, the server responds back with the response which is used to update the page. Generally, the response is in XML format, but it may be in JSON also. In simple terms, AJAX means the interaction between client and server.  AJAX enables us to partially update our web applications asynchronously. When the Ajax interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. Ajax interactions can be used to validate form entries while the user enters the data using server-side logic, to retrieve data from the server and to dynamically update data on a page. What is AJAX and How it works:- With the help of AJAX, we can create dynamic web pages which allow us to display the changes immediately without the request having to be sent to the server again. AJAX helps to send only the important data/information to server instead of the entire web page which will eliminate the load on the server. This will help in faster processing and loading of the interactive web pages. How Ajax Works – Whenever a user triggers an event on the web page like a button click. HTTPRequest is sent to the server using XMLHTTPRequest object is configured with the request parameter over the network XMLHTTPRequest makes an asynchronous request to the server.  From server side, the object which will be a servlet or an event listener handles the request which has been received from client, like data retrieved from the data base. The response is built with the requested data in the form of XML document. Using the call back function XMLHTTPRequest object receives the data, processes it and updates the HTML DOM to display the page with new data requested by client.  AJAX combines other technologies as it cannot work independently to create dynamic and interactive web pages. Below is the list of technologies which AJAX uses for building the web pages. JavaScript – When an event is triggered it invokes JavaScript function. Ajax interactions are initiated by JavaScript code, and once the interaction is complete, JavaScript updates the HTML source of the page. DOM – Is used to represent the structure of XML and HTML documents. CSS – Used in building the presentation style to display the content. XMLHTTPRequest—Used to perform asynchronous interaction from client to server using JavaScript Object. Advantages of AJAX— AJAX eliminates the need to submit the form for validation. AJAX allows us real-time form validation, as and when the user starts entering the data in the form. AJAX avoids the entire page being reloaded, as it partially updates the webpage. AJAX is based on open standards like HTML, CSS for webpage presentation. Data is sent, retrieved, and stored in XML which is fetched from the server. Data is fetched using XMLHttpRequest object.     Sending Request and Retrieving the Response:-  Instantiating an XMLHTTPRequest using   var req = new XMLHTTPRequest();  Sending the request to the server, we use open() req.open(“GET”,”test.txt”); the file can be of any type .txt or .xml req.open(“POST”, add-emp.php); GET is generally used to send small amounts of data to the server and using POST methods data is sent as part of HTTP request body. When data is sent using GET, data is sent as query URL parameter, whereas in POST data is not visible. Using send() of XMLHTTPRequest(); we can send the request to the server req.send(); Send() accepts optional parameter body which will allow us to specify the request body. Ajax GET and Post Request:- GET is typically used to retrieve the information from the server. The send() returns immediately as the request is asynchronous; hence we must check where the response exists in its life cycle before processing it further. It uses readyState property of XMLHTTPRequest; readyState is simply an integer value which describes the status of HTTP request, whenever onreadystatechange function is called when readyState property changes. Values of readyState: 0 – UNSENT – request is not yet initiated 1 – OPENED – open() successfully established server connection to fulfil the request 2 – HEADER_RECEIVED – Server has received request successfully  3 – LOADING – Processing of request is in progress 4 – DONE – Request is processed and response is ready at the server. readstatechange event is triggered every time the readyState property is changed. The HTTP status code returns status property of the XMLHTTPRequest’s response, most commonly used status code. 200 – OK Server processed request successfully  404 – Server can’t find the page requested. 503 – Server is temporarily unavailable. POST is used to submit form data to the server. Form data can be sent using FormData object or using query string as req.send(key=value1&key=value2&..&keyN=valueN). Whenever we are sending the data as query string, we need to explicitly set the request header using setRequestHeader(); Req.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”); The setrequestHeader() is called just after open() is called and before calling send(); Most commonly used request headers as part of setRequestHeader();  txt/html, text/plain, application/xml, application/json. With the help of form data we can easily construct set of key/value pairs used for representing form fields and their values are sent using XMLHTTPRequest.send().  Ajax Actions:-   Below are the list of actions that happen in AJAX. Client triggers the event, a JavaScript function is invoked and XMLHTTPRequest object is created and configured. Asynchronous call is made to server by XMLHHTPRequest, server returns the response in XML format. Response is processed using callback() of XMLHTTPRequest object and DOM is updated.  Ajax Security:-   Client-side security in AJAX –  Avoid building XML or JSON dynamically, to make XML and JSON use a safe library to keep the attributes and element data safe. Always keep the data which requires encryption at server side by using TLS/SSL. Never use eval() at the client side, always use .txt instead of .html as .txt prevents most of the XSS problems. To prevent injection style issues, always make sure that the data is encoded properly before sending. Poorly written JavaScript code will help hackers and cause security problems. Users can read JavaScript, so ensure that all the crucial business logic takes place on the server, rather than the browser. Move JavaScript that is not needed at load time to the bottom of the page to make the page load faster. Moving the JS to the end of the page will ensure the browser will display what is needed first and load the JavaScript later on. Always use minified JavaScript, as minification reduces the JavaScript size by removing unnecessary characters. Server-side security in AJAX –  Avoid writing serialization code on the server side  Always use CSRF tokens at the server side. Always use framework while using JSON or XML. Specify authentication, authorization, and other data protection either in web.xml or do it programmatically. ConclusionIn this blog we have learnt that using AJAX we can simply exchange the data asynchronously over the network; updating the page dynamically without reloading the entire content. The popularity of AJAX is increasing as it is a scripting language using JavaScript which provides numerous advantages.   AJAX is a collection of robust technologies that are used to develop dynamic web pages.  It helps us in building more responsive pages by transmitting only the required form data to the server.  One of the important objects which AJAX uses is XMLHTTPRequest object from JavaScript which helps in asynchronous communication from client and server.  Using AJAX we can significantly bring down network load and bandwidth usage by requesting only the required data.  Without AJAX, traditional web pages would take a longer time to get the data from the server.  Even if small changes were present in the web page, the entire web page would be reloaded.  AJAX offers the biggest advantage with Form which is the common element in a web page. Using AJAX, the validation is instant, with callback making a quick round trip to and from the server to retrieve and/or save data without posting the entire page back to the server. By not performing a full postback, network utilization is minimized and operations are quicker.  Ajax enabled applications will always be more responsive, faster and more user-friendly; with vastly improved speed, performance and usability. 

What Is the Purpose of AJAX in JavaScript.

9K
What Is the Purpose of AJAX in JavaScript.

Asynchronous JavaScript And Xml (AJAX) is the best solution, whenever you want to update your webpages asynchronously by exchanging the data to/from the server . It simply means that without reloading the complete webpage for your application we can update parts of the web application dynamically and asynchronously without sending the request back to the server. AJAX is the combination of XMLHttpRequest Object, JavaScript and HTML DOM (Document Object Model). 

As we already know, JavaScript allows us to add enhanced functionality and helps web pages to interact with the clients asynchronously. JavaScript mainly runs on the client side, which is known as the browser. Whenever a JavaScript function sends the request asynchronously from the client to the server, the server responds back with the response which is used to update the pageGenerally, the response is in XML format, but it may be in JSON also. In simple terms, AJAX means the interaction between client and server 

AJAX enables us to partially update our web applications asynchronously. When the Ajax interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. Ajax interactions can be used to validate form entries while the user enters the data using server-side logic, to retrieve data from the server and to dynamically update data on a page. 

What is AJAX and How it works:- 

With the help of AJAX, we can create dynamic web pages which allow us to display the changes immediately without the request having to be sent to the server again. AJAX helps to send only the important data/information to server instead of the entire web page which will eliminate the load on the server. This will help in faster processing and loading of the interactive web pages. 

How Ajax Works  

  • Whenever user triggers an event on the web page like a button click. 
  • HTTPRequest is sent to the server using XMLHTTPRequest object is configured with the request parameter over the network 
  • XMLHTTPRequest makes an asynchronous request to the server. 
  •  From server side, the object which will be a servlet or an event listener handles the request which has been received from client, like data retrieved from the data base. The response is built with the requested data in the form of XML document. 
  • Using the call back function XMLHTTPRequest object receives the data, processes it and updatethe HTML DOM to display the page with new data requested by client.  

AJAX combines other technologies as it cannot work independently to create dynamic and interactive web pages. Below is the list of technologies which AJAX uses for building the web pages. 

  • JavaScript  When an event is triggered it invokes JavaScript functionAjax interactions are initiated by JavaScript code, and once the interaction is complete, JavaScript updates the HTML source of the page. 
  • DOM – Is used to represent the structure of XML and HTML documents. 
  • CSS  Used in building the presentation style to display the content. 
  • XMLHTTPRequest—Used to perform asynchronous interaction from client to server using JavaScript Object. 

Advantages of AJAX 

  • AJAX eliminates the need to submit the form for validation. AJAX allows us real-time form validation, as and when the user starts entering the data in the form. 
  • AJAX avoids the entire page being reloadedas it partially updates the webpage. 
  • AJAX is based on open standards like HTML, CSS for webpage presentation. Data is sent, retrieved, and stored in XML which is fetched from the server. 
  • Data is fetched using XMLHttpRequest object.     

Sending Request and Retrieving the Response:-  

  • Instantiating an XMLHTTPRequest using  

 var req = new XMLHTTPRequest();  

  • Sending the request to the server, we use open() 

req.open(“GET”,”test.txt”); the file can be of any type .txt or .xml 
req.open(“POST”, add-emp.php); 

  • GET is generally used to send small amounts of data to the server and using POST methods data is sent as part of HTTP request body. When data is sent using GET, data is sent as query URL parameter, whereas in POST data is not visible. 

  • Using send() of XMLHTTPRequest(); we can send the request to the server 
    req.send(); Send() accepts optional parameter body which will allow us to specify the request body. 

Ajax GET and Post Request:- 

GET is typically used to retrieve the information from the server. The send() returns immediately as the request is asynchronous; hence we must check where the response exists in its life cycle before processing it further. It uses readyState property of XMLHTTPRequest; readyState is simply an integer value which describes the status of HTTP request, whenever onreadystatechange function is called when readyState property changes. Values of readyState: 

  • 0 – UNSENT  request is not yet initiated 
  • 1 – OPENED – open() successfully established server connection to fulfil the request 
  • 2 – HEADER_RECEIVED – Server has received request successfully 
  •  3 – LOADING  Processing of request is in progress 
  • 4 – DONE  Request is processed and response is ready at the server. 

readstatechange event is triggered every time the readyState property is changed. 

The HTTP status code returns status property of the XMLHTTPRequest’s response, most commonly used status code. 

  • 200 – OK Server processed request successfully  
  • 404 – Server can’t find the page requested. 
  • 503  Server is temporarily unavailable. 

POST is used to submit form data to the server. Form data can be sent using FormData object or using query string as req.send(key=value1&key=value2&..&keyN=valueN). Whenever we are sending the data as query string, we need to explicitly set the request header using setRequestHeader(); 

Req.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded); 

The setrequestHeader() is called just after open() is called and before calling send(); 

Most commonly used request headers as part of setRequestHeader();  

txt/html, text/plain, application/xml, application/json. 

With the help of form data we can easily construct set of key/value pairs used for representing form fields and their values are sent using XMLHTTPRequest.send().  

Ajax Actions:- 

  Below are the list of actions that happen in AJAX. 

  • Client triggers the event, a JavaScript function is invoked and XMLHTTPRequest object is created and configured. 
  • Asynchronous call is made to server by XMLHHTPRequest, server returns the response in XML format. 
  • Response is processed using callback() of XMLHTTPRequest object and DOM is updated.  

Ajax Security:- 

  Client-side security in AJAX   

  • Avoid building XML or JSON dynamically, to make XML and JSON use a safe library to keep the attributes and element data safe. 
  • Always keep the data which requires encryption at server side by using TLS/SSL. 
  • Never use eval() at the client side, always use .txt instead of .html as .txt prevents most of the XSS problems. 
  • To prevent injection style issues, always make sure that the data is encoded properly before sending. 
  • Poorly written JavaScript code will help hackers and cause security problems. 
  • Users can read JavaScript, so ensure that all the crucial business logic takes place on the server, rather than the browser. 
  • Move JavaScript that is not needed at load time to the bottom of the page to make the page load faster. Moving the JS to the end of the page will ensure the browser will display what is needed first and load the JavaScript later on. 
  • Always use minified JavaScript, as minification reduces the JavaScript size by removing unnecessary characters. 

Server-side security in AJAX   

  • Avoid writing serialization code on the server side  
  • Always use CSRF tokens at the server side. 
  • Always use framework while using JSON or XML. 
  • Specify authentication, authorization, and other data protection either in web.xml or do it programmatically. 

Conclusion

In this blog we have learnt that using AJAX we can simply exchange the data asynchronously over the network; updating the page dynamically without reloading the entire content. The popularity of AJAX is increasing as it is a scripting language using JavaScript which provides numerous advantages.   

  • AJAX is a collection of robust technologies that are used to develop dynamic web pages 
  • It helps us in building more responsive pages by transmitting only the required form data to the server.  
  • One of the important objects which AJAX uses is XMLHTTPRequest object from JavaScript which helps in asynchronous communication from client and server.  
  • Using AJAX we can significantly bring down network load and bandwidth usage by requesting only the required data.  
  • Without AJAX, traditional web pages would take a longer time to get the data from the server.  Even if small changes were present in the web page, the entire web page would be reloaded. 
  •  AJAX offers the biggest advantage with Form which is the common element in a web pageUsing AJAX, the validation is instant, with callback making a quick round trip to and from the server to retrieve and/or save data without posting the entire page back to the server. By not performing a full postbacknetwork utilization is minimized and operations are quicker.  

Ajax enabled applications will always be more responsive, faster and more user-friendly; with vastly improved speed, performance and usability. 

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

An Introduction to Angular Components

Every Application has an important building block, the UI, and a Component in Angular is the basic unit which helps to build a UI. In general user terms UI is referred to as a view. What are Components? Components are basic building blocks which consist of an HTML template that declares what renders on the page, a class written in TypeScript which defines the behaviour, a CSS selector which defines how it can be used in the template and CSS styles which define how it will look when a user views it. Representation of Components:If you’re a programmer by profession and have some fundamental knowledge of user experience, the above diagram will help you to understand about the internal structures of components. Let’s take an example to understand components in a better way, and consider that we are building a page for an application. The features in the page include the header, footer and navigation and content area. Instead of building a single page with all these features, we can choose to split the page into components, which help us to manage our application.In the above scenario, we can say that the header, footer, content area, navigation and so on are separate components of the page; but when the user views it on the website through any device, it will show as a single page.Next, we will find out how to build components, and what is the internal structure of components.The Structure of Components: Components are comprised of Template, Directives and Data bindings. Before creating a component, we should get an idea of what these are. Template - A template combines HTML with Angular mark-up, to modify HTML elements before they are displayed. It’s an HTML file which displays information. Here is an example of a Template: Directives – Directives form an important part of a component. They provide the program logic to the component. Here are some examples of directives: *ngFor, *ngIf Data Binding – Data binding is the process that establishes a connection between the application UI and business logic. Without this, no component in Angular can become functional. Here is an example of Data Binding: ‹div> Current Number is {{value1}} Current Number is {{value1 | currency}} Current Number is {{dt1}} Current Number is {{dt1 | date}} Status is {{status}} Component metadata The metadata for a component tells Angular where to get the major building blocks that it needs to create and present the component and its view. In particular, it associates a template with the component, either directly with inline code, or by reference. Together, the component and its template describe a view. Example of metadata:@Component({  selector:  app-hero-list',  templateUrl:'./hero-list. component. html',  providers:  HeroService  }) Here in the above example, the selector, template URL, and providers consist of metadata which tell where to get the major building blocks.  Next, let us learn how we can configure a component in a project. Configuration of Angular Component The easiest way to create a component is with the Angular CLI. You can also create a component manually.  Creating a component using the Angular CLIFrom a terminal window, navigate to the directory containing your application. Run the ng generate component  command, where  is the name of your new component. By default, this command creates the following: A folder named after the component A component file, .component.ts A template file, .component.html A CSS file, .component.css A testing specification file, .component.spec.ts Where  is the name of your component. Creating a component manually Navigate to your Angular project directory. Create a new file, .component.ts. At the top of the file, add the following import statement. import { Component } from '@angular/core'; After the import statement, add a @Component decorator. @Component({  }) Choose a CSS selector for the component. @Component({   selector: 'app-component-overview',  }) Define the HTML template that the component uses to display information. In most cases, this template is a separate HTML file. @Component({  selector: 'app-component-overview',   templateUrl: './component-overview.component.html',  }) Select the styles for the component's template. In most cases, you define the styles for your component's template in a separate file. @Component({   selector: 'app-component-overview',  templateUrl: './component-overview.component.html',  styleUrls: ['./component-overview.component.css']  }) Add a class statement that includes the code for the component. export class ComponentOverviewComponent {  } For more details information on creating an Angular component, the reader can go through the official website of Angular refWe are now going to learn another concept in terms of the uses of Angular components. Let’s talk about the use of Aliases for importing components. Aliases in Angular component imports  When working with Angular projects in real time, we might come across a scenario where we are required to remember a long relative path for a component in an Angular file. This often proves to be difficult, and it makes the application messy and complex to read, especially if you are new to the team. This is where Aliases come to the rescue. You might come across something like:In the above example, we should use aliases for relative paths to improve the readability of the code. To achieve this in your Angular application, all you need to do is to update the tsconfig.json file. If you look at the above configuration, the default property of the baseUrl property was updated to ‘src’ directory. Then, we added a new property called paths, which is an object containing key-value pairs representing aliases defined for the paths in our application. The above code can be rewritten as shown below: Like Aliases help in code readability, Lazy load is also a very useful Angular feature. Let’s Understand Lazy Load in terms of any programming language: As the term itself suggests, a Lazy Load is loaded late and only when needed. To understand this in a better way, consider a VIEW MORE button on any web page of an application. When we click on this VIEW MORE button, it loads the rest of the content and displays it to the user. In a similar way, in Angular applications, we have several such components which are not very important. Only when the user wants to view these components, they must be loaded. We use Lazy load in such scenarios, as using this feature will make the best use of time and space in applications. There are two main steps to setting up a lazy-loaded feature module: Create the feature module with the CLI, using the --route flag. Configure the routes. To understand in more detail, with some sample code, please go through this reference URL where it is explained very well by the Angular TeamIn the example below, the LOAD MORE Button is created using the lazy loading concept. Visitors can view more blogs only if they are interested by clicking on this button.Conclusion: I hope this blog will help readers to understand some basic concepts of Angular components and their structure. To explore more advanced concepts and delve deeper into Angular 2-11,  visit this link.
9251
An Introduction to Angular Components

Every Application has an important building block,... Read More

Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email in Node.js using the nodemailer npm package.For the email provider, we are going to use Sendinblue. Prerequisites Node.js (>v6.0.0 for nodemailer module) Code Editor (For Ex. VS Code, Atom) An account in SendinblueStart by creating a free account in Sendinblue. A Sendinblue free account offers 300 mails/day. Its setup is easy and straightforward. An introduction to Nodemailer Nodemailer, an open source project started in 2010, is annpm module for Node.js applications to send emails. Today, nodemailer is a de facto to send an email in Node.js. Highlights of Nodemailer It is a single module with zero dependencies  It supports HTML Content  Allows you to easily add attachments to messages Supports SMTP as default transport method; other supported transport methods are SES, Sendmail, Stream. OAuth2 authenticationGetting Started For this tutorial, I am using Nodejs v12.16.1 and VS Code as the Code Editor. Create a new directory nodemailer-example.  Open the terminal or cmd inside the directory and run  $ npminit --yes It will initialize a new npm package. Install dependencies Following different npm packages, we are going to use in this project. nodemailer – To send the mail express – To create APIs cors – To resolve the cross originresource sharing body-parser – To extract the body from the API request dotenv – To access the environment variables $ npm install --save nodemailer express cors body-parser dotenv This command will install all the dependencies. Now, we can start the coding. Project Structure Open the nodemailer-example in the code editor and create the following folders and files in it; not to worry, I will be explaining all the files and commands involved.  nodemailer-example    |- routes      |- mail-api.js    |- src      |- send-mail.js    |- template      |- mail.html    |- .env    |- index.js Sendinmail Setup Login to your Sendinmail account. From the top-left menu, select SMTP & API. Select the SMTP tab. Click on Create a new SMTP key. Copy the key at some safe place.  You can deactivate the SMTP key anytime. Now, open the .env file and create 2 key-value pair. USER=YOUREMAILADDRESS  PASS=xxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx USER: The email address using which you created the sendinmail account. PASS:SMTP Key By using .env file we are not exposing the credentials to the web.  Using environment variables in the project is an industrial standard.  Source Code Open the send-mail.js in the editor. Copy and paste the below code in it."use strict";  require("dotenv").config();  constnodemailer = require("nodemailer");  /**   * sendEmail   * @param{Object}mailObj - Email information   * @param{String}from- Email address of the sender   * @param{Array}to- Array of recipients email address   * @param{String}subject - Subject of the email   * @param{String}text - Email body   */  constsendEmail = async (mailObj) => {  const{ from, to, subject, text } = mailObj;  try {  // Create a transporter  lettransporter = nodemailer.createTransport({  host:"smtp-relay.sendinblue.com",  port:587,  auth: {  user:process.env.USER,  pass:process.env.PASS,        },      });  // send mail with defined transport object  letinfo = awaittransporter.sendMail({  from:from, // sender address  to:to, // list of receivers  subject:subject, // subject line  text:text, // plain text body      });  console.log(`Message sent: ${info.messageId}`);  return`Message sent: ${info.messageId}`;    } catch (error) {  console.error(error);  thrownewError(  `Something went wrong in the sendmail method. Error: ${error.message}`      );    }  };  module.exports = sendEmail; Code Walk Through In the beginning, we are importing dotenv to get the environment variables from the .env file and nodemailer to send the email. The sendEmailfunction accepts an object. This object has from, to, subject, text fields. Please note that, from and USER must be same. The nodemailer.createTransportreturns a mail object. The transporter variable is storing the mail object.  let transporter = nodemailer.createTransport({       host: "smtp-relay.sendinblue.com",       port: 587,       auth: {         user: process.env.USER,         pass: process.env.PASS,       },     });Open SMTP tab in your sendinmail account and cross check the host and port.In the auth object, we are passing the user and password from the environment variable.Send the mail using sendMail method.// send mail with defined transport object     let info = await transporter.sendMail({       from: from, // sender address       to: to, // list of receivers       subject: subject, // Subject line       text: text, // plain text body     });It returns a Promise of Send Message Info. In the end, it is returning the message id.  Express Route The sendEmail method is ready.  Let’s create an express route for it. This is the API endpoint using which we can access the sendEmail function. Open the mail-api.js in the code editor and paste the below code. constexpress = require("express");  constrouter = express.Router();  constsendMailMethod = require("../src/send-mail");  // Post request to send an email  router.post("/sendmail", async (req, res) => {  try {  constresult = awaitsendMailMethod(req.body);  // send the response  res.json({  status:true,  payload:result          });      } catch (error) {  console.error(error.message);  res.json({  status:false,  payload:"Something went wrong in Sendmail Route."          })      }  }) module.exports = router; The express framework provides a Router method to create different HTTP methods. Here, we have created a POST method to send the mail.  Instead of extracting the req.body parameters, we passed it as it is. The benefit of this approach is that if there is a change in argument or position, then we would not have to change it in all the places.  In the end, we are exporting the router. Now, this can be used in the server side. Express Server Now, it’s time to create a server and expose the routes on it. Open the index.js and paste the below code in it. "use strict";  constexpress = require("express");  constbodyParser = require("body-parser");  constcors = require("cors");  constapp = express();  constmailAPI = require("./routes/mail-api.js");  // Express body parser  app.use(cors());  app.use(bodyParser.json());  app.use(  bodyParser.urlencoded({  limit:"50mb",  extended:false,  parameterLimit:50000    })  );  // use the routes specified in route folder  app.use("/api/v1", mailAPI);  constport = process.env.PORT || 4444;  //listen to the server  app.listen(port, function () {  console.log(`listening to the port ${port} .....`);  }); The route is available on /api/v1/sendmail. Run the server. $ node index.js  listening to the port 4444 ..... Send an Email using API There are couple of methods to test the API. Using the Postmanor using the Curl command. Using Postman Install Postman on your machine if it is not installed. Create a POST request. URL: http://localhost:4444/api/v1/sendmail Content Type: JSON – Body tab > select JSON from dropdown Request Body:  {  "from": "hello@schadokar.dev",  "to": ["shubham@schadokar.dev"],  "subject": "Mail from Nodemailer",  "text": "Sending an email using nodemailer package."  } Hit Send. Make sure the server is running. On Success, the response returns the message id. Now, check your mailbox. If you are unable to find the mail in your Inbox, check the promotional mail folder. Using Curl CommandOpen the terminal or cmd.In the below curl command, change the parameters and enter.curl -X POST http://localhost:4444/api/v1/sendmail -H "Content-Type:application/json" -d '{"from": "hello@schadokar.dev","to": ["shubham@schadokar.dev"],"subject": "Mail from Nodemailer", "text": "Sending an email using nodemailer package."}'In this example, we have sent a simple text message to the recipient.  Nodemailer also gives you an option to send the message in HTML format. Mail template Open the mail.html in the code editor and paste the below code. 
6797
Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email ... Read More

Full Stack Development – the Hottest Developer Skill for the Digital Age

With over 1.7 billion websites worldwide and 4.54 billion people using the internet actively, the need for heightened customer experience is on the rise. This is one of the major reasons why professionals who are adept at handling both the client-side and server-side interfaces of an application/website have become more important than ever. It has been estimated that by the next decade, there will be 300,000 new developer jobs in US. The Full Stack developer role is the No.1 position to be filled in 2020 according to 38% of hiring managers. This is closely followed by the role of a back-end developer.Handsome pay packagesThe average annual salary for a full-stack developer is about $110,737 per annum. Even beginners are offered about $58,000 per year and on the other hand, experienced professionals would earn up to $188,253 per year.These professionals are paid handsomely because enterprises are aware that a full stack developer does the job of two professionals (back-end and front-end developer).Plenty of growth opportunitiesAs per reports by The United States Bureau of Labor Statistics, full-stack development job opportunities will increase from 135,000 to 853,000 by the year 2024. This is quite promising for aspiring full stack developers as an ocean of opportunities will be available for them in both startups as well as in multi-national organizations.Skills to become a Full Stack developerBecoming a full-fledged full stack developer is not child’s play. It takes a wide range of skills to become a good full stack developer. Below are the mandatory skills:Front-end skills: They should be well-versed with basic front-end technologies like HTML5, CSS3, and JavaScript. They should also be comfortable working with front-end frameworks or third-party libraries such as JQuery, SASS, and AngularJS.Programming languages: They should be aces in at least one server-side coding language like Java, Python, Ruby or .Net.Databases: They should be efficient at handling data from databases like MySQL, MongoDB, Redis, Oracle and SQLServer.Version control systems (VCS): Full stack developers must be aware of Git so that they can make appropriate changes to the codebase.Basic design skills: Awareness about the basic prototype design and UI/UX design is essential to become a successful full stack developer.Server and API: They should have adequate exposure to Apache or Linux servers as well as web services.The way forward for Full Stack developersThe growing demand for full-stack developers is due to the ample benefits they offer to organizations. With technology evolving at a rapid pace, foresighted companies will keep adding them to their workforces. Full stack development became the No.1 developer skill because these developers are trained to multi-task various technologies and products. For aspiring full stack developers out there, now is the best time to make the most of these opportunities.Real products require real challenges. Check out our live online workshops and build your portfolio of projects.
4858
Full Stack Development – the Hottest Develop...

With over 1.7 billion websites worldwide and 4.54 ... Read More