How to send sms using nodejs with jquery ajax and nexmo Api

How to send SMS using nodejs

Nowadays web applications send the SMS text messages to users for authentication, to reset a password or to verify a user’s mobile number. There are many services available to send SMS on the user’s mobile phone. In this tutorial, Nexmo service is used to send SMS using nodejs.

send sms using nodejs application

Following tasks are performed in this tutorial:

1. Create an account on Nexmo website

2. Generate NodeJS, express application

3. Install nodemon and nexmo modules

4. Create HTML form so the user can enter the mobile number

5. Add AJAX code to send the request to the server

6. Add route to send SMS using Nodejs

sedn sms using nodejs - main image

Create an account on Nexmo website

Nexmo is a popular service, used to send an SMS, make or receive a call, verify a user, check a number. To create an account on nexmo website, visit, and Signup.

send sms using nodejs - nexmo signup

Enter role and preferred programming language, select SMS as product. Click Done button.

send sms using nodejs - nexmo signup for service

After login, open the dashboard. Find API key and API secret on the dashboard. API_KEY and API_SECRET are pasted in index.js file.

Nexmo Dashboard

send sms using nodejs - nexmo dashboard image

 

Generate NodeJS Express application

Visit the NodeJS website. Download and install NodeJS. NPM or Node Package Manager is also installed with NodeJs installation.

NPM is used to manage nodejs modules and dependencies. Install Express Generator. Express generator is used to generate the express application skeleton.

npm install express-generator -g

With Express Generator installation Express command-line tool is installed. Open the directory where you want to create the application.

express send-sms-using-nodejs --view=pug

send sms using nodejs - generate project

Install the required modules

cd send-sms-using-nodejs && npm install

Install Nodemon

Nodemon module restarts the nodejs application if a file change is detected in the directory.

npm install nodemon --save

Install the Nexmo module

Nexmo module is a RESTful API wrapper for Nexmo.

npm install nexmo

View running application

Run the nodemon module. On command line type.

nodemon

Open the browser and add the following URL.

http://localhost:3000

Create HTML form

Open layout.pug file in views directory.

Update layout.pug file

doctype html
html
  head
    title= title
    link(href='https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css', rel='stylesheet')
    script(src='https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js')
    link(rel='stylesheet', href='https://use.fontawesome.com/releases/v5.1.0/css/all.css')
  body
    block content
    script(src="https://code.jquery.com/jquery-3.3.1.min.js")
    script(src='/javascripts/app.js')

Update index.pug file

The index.pug file extends layout.pug file. Add a form.

extends layout

block content
  .container
  br
  .row.justify-content-center
    .col-12.col-md-10.col-lg-8
      h1 Send SMS using Nodejs and Nexmo API
  .row.justify-content-center
    .col-12.col-md-10.col-lg-8
      .alert.alert-danger.d-none#error
        strong Error! 
        | Mobile number is required.
  .row.justify-content-center
    .col-12.col-md-10.col-lg-8
      form.card.card-sm(action="send" method="post")
        .card-body.row.no-gutters.align-items-center
          .col-auto
          // end of col
          .col
            input.form-control.form-control-lg.form-control-borderless(type='text', id='mobile' placeholder='Enter Mobile Number', required)
          // end of col
          .col-auto
            button.btn.btn-lg.btn-success(type='button' id="sendsms") Send SMS

 

send sms using nodejs application

AJAX code to send SMS using nodejs

Open javascripts directory in public directory and add a file app.js.

$(function(){
    $('#sendsms').on('click', function(){
        let mobile = $("#mobile").val();
        if(mobile){
            $.post( "/send", { mobile: mobile })
            .done(function( data ) {
                if(data['success']){
                    $("#error").removeClass('alert-danger d-none').addClass( "alert-success").html('Message sent successfuly');
                }else{
                    $("#error").removeClass('alert-success d-none').addClass( "alert-danger").html('Message sending failed. Try again');
                } 
                
            });
        }else{

           $("#error").removeClass('d-none');
        }
    });
});

After the user enters Mobile number and clicks Send SMS button. OnClick method of the button is triggered. Mobile number is assigned to a variable mobile. 

A post request is sent to Send route. If the message is sent successfully a success message is displayed to the user otherwise an error message is displayed.

send sms using nodejs - error message

Add send rout to send SMS using nodejs

Open index.js file in routes directory. Include nexmo module and assign API Keys on top of the file.

const Nexmo = require('nexmo')
const nexmo = new Nexmo({
  apiKey: 'API_KEY',
  apiSecret: 'API_SECRET'
});

Add a new HTTP POST route

router.post('/send', function(req, res, next) {
  const from = 'Example Website';
  const to =  req.body.mobile;
  const text = 'Welcome to our website.';
  nexmo.message.sendSms(from, to, text);
  res.json({success : "true", status : 200});
});

In this route, from the field is set to Example WebsiteTo is the number that receives SMS message. Text is the content sent to the receiver.

Nexmo module has a message.sendSms method. From, To, and Text params are passed to this method. The success message is displayed after sending SMS.

send sms using nodejs success message

The message is received successfully on the mobile phone.

Run the application

If the application is not already running then on command line type

nodemon

Open browser, type

http://localhost:3000

Summary

To summarize, in this tutorial you have learned, how to send SMS using NodeJS and Nexmo API. An account is created on Nexmo website and SMS was sent using APIs sendSMS method.

You can clone or download the source code of the tutorial from GitHub repo. Please subscribe to our newsletter. Like us on Facebook or follow on twitter to stay updated on upcoming articles.

 

Related Articles:

 

Previous Article: