如何在Node.js中使用Vonage的SMS API发送短信
短信服务(SMS)是组织用来与客户沟通的最佳营销策略之一。在你的手机或网络应用中使用短信可以让你接触到更多的受众,因为人们往往比电子邮件更频繁地检查他们的信息收件箱。
Vonage的SMS API允许开发者轻松地将信息服务整合到应用程序中。
该API的好处包括。
- 支持本地电话号码。
- 低延时。
- 高交付率。
- 支持现代网络技术。
目标
本文将使你能够使用Vonage的SMS API将SMS功能集成到Node.js应用程序中。
目录
- 简介
- 设置一个Vonage账户
- 设置一个Node应用程序
- 安装依赖项
- 实现SMS功能
- 总结
设置Vonage账户
- 导航到Vonage的网站,免费创建一个账户。该平台允许你以2美元的价格进行免费试用,之后你需要支付更多费用。
- 通过输入你的电子邮件地址和一个强大的密码来创建一个账户。
- 在电话号码领域,提供一个有效的号码,我们将用它来测试应用程序。
- 由于我们将使用Node.js,所以选择它作为目标编程语言。
- 点击短信,然后等待平台设置你的账户。
你已经成功创建了一个Vonage账户;你的仪表板应该是这样的。

创建Node.js应用程序
启动应用程序
通过运行以下命令设置Node.js应用程序。
npm init
该命令将为我们的应用程序创建一个空的package.json 文件。package.json 将保存项目的元数据,包括依赖性、脚本和版本。
安装依赖项
接下来,我们将安装所需的依赖项。
我们将使用
express作为我们的 Node.js 后台框架,EJS作为我们的模板引擎,body-parser来解析 HTTP 请求体,nexmo API来发送消息,socket.io来请求发送消息的交付报告。
要安装这些依赖项,请在终端运行以下命令。
npm install –save express, nexmo, eggs, body-parser, socket.io, fetch
Nodemon
我们将需要nodemon ,以监测应用程序中的变化,并在检测到变化时重新启动服务器。我更喜欢在全局范围内安装nodemon 。要安装nodemon,运行下面的命令。
npm install -g nodemon
我们都准备好了。现在,让我们开始编码吧
实施
首先,我们需要创建我们应用程序的入口点文件。我将把它命名为app.js 。
你可以使用
init命令设置应用程序的入口点,或者在package.json文件中手动设置。
在app.js ,我们将导入我们的依赖项,如下图所示。
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const Nexmo = require('nexmo');
const socketio = require('socket.io');
const fetch = require("node-fetch");
接下来,我们用express 来初始化应用程序,并设置我们的模板引擎,EJS 。EJS 允许我们为我们的视图使用.html 扩展。
我们将在app.js 文件中添加以下代码。
const app = express()
//Setting up the body parser middleware and ejs template engine
app.set('view-engine', 'html');
app.engine('html', ejs.renderFile);
//public folder setup
app.use(express.static(__dirname + '/public'));
//body parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true});
将index 路线指定为index.html ,因为应用程序将只有一个页面。
//index route
app.get('/', (request, response) =>{
response.render('index.html');
});
创建我们的视图
我们将创建一个名为views 的文件夹,在那里我们将存储我们的模板文件。在该文件夹中,创建一个index.html 文件。它将包含要发送的phone number 和message 的输入字段。
下面是index.html 的代码。
<!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>Send SMS APP</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<h2>Send Message</h2>
<!-- phone number input field -->
<input type="tel" name="number" class="input" id ="number" placeholder="Enter phone number">
<!-- message input field -->
<textarea rows="4" cols="50" name="msg" id ="message" placeholder="Enter message here..."></textarea>
<!-- submit button -->
<div class="button-container">
<button type="button" id ="button" value="Send">Send Message</button>
</div>
<!-- Socket.io response in a paragraph -->
<p class="response"></p>
</div>
<!-- link to js scripts and socket -->
<script src="/socket.io/socket.io.js"></script>
<script src="js/main.js"></script>
</body>
</html>

客户端JavaScript驱动代码
我们将在我们应用程序的根部创建一个公共文件夹。在这个公共文件夹中,我们将创建一个main.js 文件,包含获取用于触发发送短信功能的变量的JavaScript代码。
// phone number
const phoneNumber= document.getElementById('number'),
//message to send
textMessage = document.getElementById('message'),
//send button
button = document.getElementById('button'),
//response field
response = document.querySelector(".respose");
添加发送功能
由于我们已经在HTML表单中添加了一个send button ,我们需要在按钮上附加一个EventListener ,以触发send() 功能。
下面的代码块显示了这个功能的实现。
button.addEventListener('click', send, false);
function send() {
// getting value form the variabled fetched
const number = phoneNumber.value.replace(/\D/g, '');// eliminate non-numeric characters
const text = textMessage.value;
// Making a post request with the data to the our server
fetch('/', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
// convert the request body into a string
body: JSON.stringify({ number, text })
}).then(function (res){
//log the response
console.log(res);
}).catch(function(err){ //cathc any error found
//console log the error
console.log(err);
});
}
实现Nexmo
首先,我们将通过提供我们的apiKey 和secret 来初始化Nexmo。
//init out nexmo
const nexmo = new Nexmo({
apiKey: 'YOUR API-KEY',
apiSecret: 'API-SECRET',
}, {debug:true});
我们需要向服务器发出一个帖子请求。在app.js 文件中,添加以下代码,以捕捉post request ,并使用Nexmo ,将信息发送到指定的号码。
//catch post from our main.js
app.post('/', (request, response) =>{
const phoneNumber = request.body.number;
const textMessage = request.body.text;
const from = 'Vonage APIs';
const to = phoneNumber;
const text = textMessage;
nexmo.message.sendSms(from, to, text, {type:'unicode'}, (error,responseData) =>{
if(error){
console.log(error)
}else{
console.dir(responseData);
//get phone number into an object to be sent to the client
const data = {
number: responseData.messages[0]['to']
}
//send response to client using socket
io.emit('smsStatus', data);
}
});
});
接下来,我们将向客户端发送响应数据,以显示短信是否被成功发送。要做到这一点,我们将使用io.emit() 函数。
io.emit('smsStatus', data)
为了接收数据并将其嵌入我们的索引页面,我们在main.js 文件中使用以下代码。
const socket = io();
socket.on('smsStatus', function(data){
if(data.error){
//in case of an error response
response.innerHTML = '<strong>Failed!</strong><h5> Messae Failed ' + data.error + '</h5>';
}else{
// if the sms is sent successfully
response.innerHTML = '<strong>Success!</strong><h5>Text message sent to ' + data.number + '</h5>';
}
});

为了启动我们的服务器,我们将定义一个端口,我们的应用程序将从这个端口在本地主机上运行。
//Port number
const port = 3000;
//start server
const server = app.listen(port, () =>{
console.log(`Server started on port ${port}`);
});

总结
我们学会了如何使用Vonage的SMS API,方法是创建一个账户,设置SMS API,并使用API向一个提供的号码发送消息。用于测试的号码必须在你的账户下注册。
注意,这只适用于非高级用户。我们还学习了如何使用sockets.io在服务器和客户端应用程序之间进行通信。