Welcome folks today in this blog post we will be sending OTP SMS
messages to Mobile number using fast2sms
api in node.js
and express
using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to initialize a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i fast-two-sms
Now you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
const fast2sms = require("fast-two-sms"); var express = require("express"); const bodyparser = require("body-parser"); const app = express(); app.use(bodyparser.urlencoded({ extended: false })); app.use(bodyparser.json()); app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); app.post("/sendmessage", (req, res) => { console.log(req.body.message); console.log(req.body.number); sendMessage(req.body.message, req.body.number, res); }); function sendMessage(message, number, res) { var options = { authorization: "###yourapikey###", message: message, numbers: [number], }; // send this message fast2sms .sendMessage(options) .then((response) => { res.send("SMS OTP Code Sent Successfully"); }) .catch((error) => { res.send("Some error taken place"); }); } app.listen(5000, () => { console.log("App is listening on port 5000"); }); |
As you can see in the above code we are importing the fast2sms
module and then we are showing the index.html
file when the users goes to the /
home page and then we are making the POST
request at the /sendmessage
and here we are making the post
request to the fast2sms
api and then here we are using the API Key
inside the fast2sms
dashboard. And then we are using the fast2sms
module and inside it we are using the sendMessage()
method to send the SMS OTP
message and it returns the promise and inside it we are showing the message to the user that sms
has been sent successfully.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/sendmessage" method="post"> <input type="text" name="number" placeholder="Enter Mobile Number" required id=""> <input type="text" name="message" placeholder="Enter your message" required id=""> <button type="submit">Send Message</button> </form> </body> </html> |
As you can see inside the index.html
file we are having two input fields
where we allow the user
to write the message
and then we have the input field to allow the user
to input the mobile number
and then we have the button to send
the message.