node api框架

Short Message Service (SMS) is not a new technology, and has been around since even before World Wide Web was born. Now with APIs, you can easily integrate SMS with web technologies. With the SMS-enabled web you can build variety of products and services such as user authentication, alerts, notifications, general communication tools and bots.

短消息服务(SMS)并不是一项新技术,并且早在万维网诞生之前就已经存在。 现在,借助API,您可以轻松地将SMS与Web技术集成在一起。 使用启用了SMS的Web,您可以构建各种产品和服务,例如用户身份验证,警报,通知,常规通信工具和漫游器。

In this tutorial, I will walk you through how to build a simple web app that sends SMS messages using Node.js, Express, and Nexmo SMS API.

在本教程中,我将引导您如何构建一个简单的Web应用程序,该应用程序使用Node.js,Express和Nexmo SMS API发送SMS消息。

Additionally, to make the web app feel more interactive, let’s also implement W3C Web Notifications API for the front-end UI to display the SMS delivery confirmation message with using Socket.IO!

另外,为使Web应用程序更具交互性,我们还为前端UI实现W3C Web Notifications API ,以使用Socket.IO显示SMS传递确认消息!

You can view the source code on GitHub and run the demo locally to see it in action!

您可以在GitHub上查看源代码,并在本地运行演示以查看实际效果!

设置您的应用 ( Setting Up Your App )

You need to have Node.js installed on your machine to get started! First, create your app directory then set up your app. On terminal:

您需要在计算机上安装Node.js才能开始! 首先,创建您的应用程序目录,然后设置您的应用程序。 在终端上:

$npm init

Then follow the command line instruction to create a package.json file, which defines your app.

然后按照命令行说明创建一个package.json文件,该文件定义了您的应用程序。

安装模块依赖项 (Installing Module Dependencies)

Now you need to install the modules the app will depend upon. To build a core app, use npm to install nexmo-node, Express.js, body-parser, and ejs. For the additional feature, get Socket.IO too.

现在,您需要安装应用程序将依赖的模块。 要构建核心应用程序,请使用npm安装nexmo-node, Express.js ,body-parser和ejs 。 对于附加功能,也请获取Socket.IO。

$npm install nexmo express body-parser ejs socket.io --save

创建应用程序结构 (Creating App Structure)

Create some directories for the files you are going to add. This is all up to you, but here is the example I am using in this tutorial:

为要添加的文件创建一些目录。 这完全取决于您,但是这是我在本教程中使用的示例:

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

├── public
│   ├── css
│   │   └── style.css
│   ├── images
│   │   └── icon-nexmo.png
│   └── js
│       └── app.js
├── server
│   └── index.js
└── views
│   └── index.html
└── package.json

通过Express服务Web应用 ( Serving the Web App with Express )

Now, let’s setup a HTML web page that serves out a form with a phone number field and a message field using Express, which is a robust web application framework for Node.js.

现在,让我们使用Express来建立一个HTML网页,该表格提供带有电话号码字段和消息字段的表单,这是Node.js的强大Web应用程序框架。

Create an index.js file:

创建一个index.js文件:

'use strict';const express = require('express');
const app = express();
const server = app.listen(4000);

Also, use body-parser (the middleware to parse form input onto a body property of the request) and ejs (HTML templating tool) to configure the Express app:

另外,使用body-parser (中间件将表单输入解析为请求的body属性)和ejs (HTML模板工具)来配置Express应用:

const bodyParser = require('body-parser');
const ejs = require('ejs');app.set('views', __dirname + '/../views');
app.set('view engine', 'html');
app.engine('html', ejs.renderFile);
app.use(express.static(__dirname + '/../public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Serving HTML:

提供HTML:

app.get('/', (req, res) => {res.render('index');
});

用户界面HTML (User Interface HTML)

Now create an index.html under /views to build the user-interface. Make sure you include a JavaScript file, js/app.js in <script>.

现在,在/ views下创建index.html来构建用户界面。 确保在<script>包含一个JavaScript文件js / app.js。

In the html file, create a few form input fields with a button:

在html文件中,使用按钮创建一些表单输入字段:

<input type="tel" name="number" placeholder="15551231234">
<input type="text" name="text" placeholder="Hello">
<input type="button" value="Send SMS">

Notice the type attributes in each <input> element- For phone number, use type="tel", and for the message text, use the regular type="text". By setting right input type, browsers on touch devices automatically pops up a right type of keyboard for an improved user experience. For instance, when the browser sees type="tel", it serves a number pad.

注意每个<input>元素中的type属性-对于电话号码,请使用type="tel" ,对于消息文本,请使用常规的type="text" 。 通过设置正确的输入类型,触摸设备上的浏览器会自动弹出正确的键盘类型,以改善用户体验。 例如,当浏览器看到type="tel" ,它将提供数字键盘。

The entire HTML looks like this:

整个HTML如下所示:

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>SMS Web App Demo</title><link rel="stylesheet" href="css/style.css">
</head>
<body><header> <h1>Text Anybody</h1></header><section id="main" role="main"><p class="intro">Enter a number, begins with a country code</p><form><input type="tel" name="number" placeholder="15551231234" required><input type="text" name="text" placeholder="Hello"><input type="button" value="Send SMS"></form></section><p class="response"></p><!-- Socket.io: This is optional. will be explained later! --><script src="/socket.io/socket.io.js"></script> <!-- Your JS file --><script src="js/app.js"></script>
</body>
</html>

To see the entire markup and CSS, please refer the source code on GitHub.

要查看整个标记和CSS,请参考GitHub上的源代码 。

处理表格提交 ( Handling the Form Submission )

Create app.js in /public/js.

/public/js创建app.js。

First, get the DOM object for each form input elements:

首先,为每个表单输入元素获取DOM对象:

var numberField = document.querySelector('input[name=number]');
var textField = document.querySelector('input[name=text]');
var button = document.querySelector('input[type=button]');
var msg = document.querySelector('.response');

Note: Notice that I am using ES6 for Node.js, while using ES5 for the front-end code, because not every ES6/ES2015 feature has been supported by modern browsers yet. If you would like to use ES6 all the way, I recommend Babel. However I am not covering it in this article.

注意:请注意,我将ES6用于Node.js,而将ES5用于前端代码,因为现代浏览器尚未支持所有ES6 / ES2015功能 。 如果您想一直使用ES6,建议您使用Babel 。 但是,我不在本文中介绍。

Then, listen to the events. Let’s make the form submittable by either hitting a Return key or pressing the button:

然后,听事件。 让我们通过单击Return键或按按钮使表单可提交:

textField.addEventListener('keyup', function(e) {if ((e.keyCode || e.charCode) === 13) send();
}, false); // when a user presses a Return keybutton.addEventListener('click', send, false); // when a user click the "Send" button

Now, let’s define the send function to submit the input values to the Node code. First, grab the values from the inputs.

现在,让我们定义send函数,以将输入值提交给Node代码。 首先,从输入中获取值。

function send() {var number = numberField.value.replace(/\D/g,''); // Remove all non-numeric charsvar text = textField.value;// ... will send the form using fetch here
}

Next, post the values to server using the Fetch API.

接下来,使用Fetch API将值发布到服务器。

好了! 通过Fetch API发送表单 (So Fetch! Sending Form via Fetch API)

For last decade or so, we have been using XMLHttpRequest for AJAX requests But now is the time to say good-bye to the good old XHR, and say hello to this shiny new Fetch API to make requests to your server!

在过去十年左右的时间里,我们一直在使用XMLHttpRequest进行AJAX请求,但是现在是时候告别旧的XHR,并向这个崭新的Fetch API致以问候,以向您的服务器发出请求!

Now, POST the phone number and the message text as JSON using the Fetch API:

现在, POST电话号码和JSON使用提取API消息文本:

fetch('/', {method: 'post',headers: {'Content-Type': 'application/json'},body: JSON.stringify({number: number, text: text})
})
.then(function(res){ console.log(res) })
.catch(function(error){ console.log(error)});

As of 2016, if you want to support Safari version 10 or older, you still need to use XHR as the fallback for now.

从2016年起,如果要支持Safari 10或更早版本,则仍然需要使用XHR作为后备。

通过Express接收表单值 (Receiving the Form Values with Express)

Now going back to the server-side index.js, and add these lines of code to take the form input values from the request:

现在回到服务器端index.js ,并添加以下代码行以采用请求中的输入值形式:

app.post('/', (req, res) => {res.send(req.body);console.log(req.body);let toNumber = req.body.number;let text = req.body.text;// Sending SMS via Nexmo ---
});

Let’s run this code once and see if this works fine.

让我们运行一次此代码,看看是否可以正常工作。

$ node server/index.js

Then, go to http://localhost:4000 in your browser. Try sending something.

然后,在浏览器中转到http:// localhost:4000 。 尝试发送一些东西。

Once the form is posted successfully, you should see the console.log value like this on terminal:

表单成功发布后,您应该在终端上看到如下所示的console.log值:

{ number: '14155551234', text: 'Hello!' }

Next, let’s use Nexmo SMS API to actually send messages to the phone number!

接下来,让我们使用Nexmo SMS API实际将消息发送到电话号码!

使用Nexmo SMS API ( Using the Nexmo SMS API )

The Nexmo SMS API allows you to send and receive a high volume of SMS anywhere in the world. Once you get your virtual phone number, you can use the API to manage outbound messages ("sending") and inbound messages (“receiving”). In this app, the API will be used for outbound messages.

Nexmo SMS API使您可以在世界任何地方发送和接收大量SMS。 获得虚拟电话号码后,就可以使用API​​管理出站消息(“发送”)和入站消息(“接收”)。 在此应用中,API将用于出站消息。

To get started with SMS, sign up for a Nexmo account to get your virtual number, as well as your API credentials. Once you signed up, go to your Dashboard to get your Nexmo virtual number on Numbers, and API key and secret on Settings section.

要开始使用SMS,请注册一个Nexmo帐户以获取您的虚拟号码以及API凭据。 注册后,转到控制台 ,在Numbers上获取Nexmo虚拟号码 ,在Settings区域上获取API密钥和密码。

将Nexmo REST API客户端用于Node.js (Using the Nexmo REST API Client for Node.js)

You should have nexmo-node installed for your web app in the very beginning of this tutorial, but if not, install with npm.

在本教程的开始部分,您应该已为Web应用程序安装了nexmo-node ,但如果没有安装,请使用npm进行安装。

$npm install nexmo --save

In your index.js, initialize with your credentials:

index.js中 ,使用您的凭据进行初始化:

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

发送短信 (Sending an SMS Message)

Then, in your POST method route that you have defined earlier, grab a phone number and a message from the web form, and send an SMS to the number from your Nexmo virtual number (NUMBER):

然后,在您之前定义的POST方法路由中,从Web表单中获取一个电话号码和一条消息,然后从Nexmo虚拟号码( NUMBER )向该号码发送短信:

app.post('/', (req, res) => {res.send(req.body);const toNumber = req.body.number;const text = req.body.text;nexmo.message.sendSms(NUMBER, toNumber, text, {type: 'unicode'},(err, responseData) => {if (err) {console.log(err);} else {console.dir(responseData);// Optional: add socket.io -- will explain later}});});

Now, try sending an SMS to a real phone number (or your Google Voice number) using your app! If everything works, you should receive SMS messages! Try emoji too. When you specify the SMS message type to "unicode" you are able to send and receive unicode including emojis!

现在,尝试使用您的应用将短信发送到真实的电话号码(或您的Google语音号码)! 如果一切正常,您应该会收到短信! 也尝试表情符号。 当您将SMS消息type指定为"unicode"时,便可以发送和接收包括表情符号在内的unicode!

You can stop this tutorial right here, or proceed to add extra features!

您可以在此处停止本教程,或继续添加其他功能!

附加:通过Socket.io和Web通知UI使应用程序更具交互性 ( Extra: Making the App More Interactive with Socket.io and Web Notifications UI )

The Nexmo SMS API returns a payload that indicates if the result of the request. Now, let’s add more features to display the sent status UI. (Note: This status indicates that the SMS is successfully sent by you via Nexmo, and not an actual delivery receipt from the recipient's carrier. To access the actual delivery receipt, read the tutorial on Nexmo.com.)

Nexmo SMS API返回指示请求结果是否有效的有效负载。 现在,让我们添加更多功能来显示已发送状态UI。 ( 注意:此状态表示SMS是由您通过Nexmo成功发送的,而不是来自收件人承运人的实际收货收据。要访问实际的收据,请阅读Nexmo.com上的教程 。

What you are going to do is:

您要做的是:

  1. Pass the API response data from the server to the UI with Socket.IO使用Socket.IO将API响应数据从服务器传递到UI
  2. Display the data on a desktop notification with Web Notifications API使用Web Notifications API在桌面通知上显示数据

使用Socket.IO在浏览器上显示服务器响应 (Displaying a Server Response on Browser with Socket.IO)

To display the SMS confirmation sent from server on browser, you are going to use Socket.IO so that the server can talk to browsers. You need to use both server API and client API to be able to communicate in real-time.

要在浏览器上显示从服务器发送的SMS确认,您将使用Socket.IO,以便服务器可以与浏览器对话。 您需要同时使用服务器API和客户端API才能进行实时通信。

服务器端 (Server Side)

You should have installed Socket.io at the beginning of the tutorial so let’s go ahead and initialize a socket.io instance in index.js:

您应该已经在本教程的开头安装了Socket.io,所以让我们继续在index.js中初始化一个socket.io实例:

const socketio = require('socket.io');
const io = socketio(server);
io.on('connection', (socket) => {console.log('Connected');socket.on('disconnect', () => {console.log('Disconnected');});
});

Socket.IO lets you emit and receive any events you want. Let’s emit an event in the sendSms callback, where you see the comment that says, // Optional using emit(eventName, eventData):

Socket.IO使您可以发出和接收所需的任何事件。 让我们在sendSms回调中发出一个事件,您会在其中看到注释, // Optional使用generate emit(eventName, eventData)

let data = {id: responseData.messages[0]['message-id'], number: responseData.messages[0]['to']};
io.emit('smsStatus', data);

In the code sample above, you are emitting the message-id, an ID of the submitted SMS message and the phone number your request was sent to. These data come from the Nexmo SMS API response, and the response also gives you more information of the status of the request and costs of the SMS.

在上面的代码示例中,您将发出message-id ,提交的SMS消息的ID和您发送请求的电话号码。 这些数据来自Nexmo SMS API响应,该响应还为您提供有关请求状态和SMS成本的更多信息。

客户端 (Client Side)

Now, you need to make browsers receive the event from the server. First, include the socket.io.js in index.html:

现在,您需要使浏览器从服务器接收事件。 首先,将socket.io.js包含在index.html中

<script src="/socket.io/socket.io.js"></script>

Then in the client, app.js, receive the smsStatus event:

然后在客户端app.js中 ,接收smsStatus事件:

var socket = io();
socket.on('smsStatus', function(data) {displayStatus('Message ID ' + data.id + ' successfully sent to ' + data.number);
});

Next, write the displayStatus function that displays the SMS callback data. You can just print it out as a simple HTML text in the browser, however, let’s display it as a desktop notification.

接下来,编写显示SMS回调数据的displayStatus函数。 您可以在浏览器中将其打印为简单HTML文本,但是,让我们将其显示为桌面通知。

在桌面通知中显示来自服务器的数据 (Displaying Data from the Server in Desktop Notifications)

The W3C Web Notifications API allows web browsers to display notifications, even when the browser window is in background. Since this feature is supported (or not) by browser vendors, each browser has slightly different UI.

W3C Web Notifications API允许Web浏览器显示通知,即使浏览器窗口处于后台。 由于浏览器供应商支持(或不支持)此功能,因此每个浏览器都有略有不同的UI。

Each browser provides a built-in permission UI for the API, so that the user can control which web pages can send them notifications. When the page is loaded for the first time, a browser asks a user the permission. Your page can send notifications only after the user has granted permission.

每个浏览器都为API提供内置的权限UI,以便用户可以控制哪些网页可以向其发送通知。 首次加载页面时,浏览器会询问用户许可。 您的页面只有在用户授予权限后才能发送通知。

To request permission, add these lines in your app.js,

要请求权限,请在app.js中添加以下行,

Notification.requestPermission().then(function(status) {console.log(status); // when a user granted, status == 'granted', otherwise, 'denied'
});

Then create a displayStatus function that passes the data received via Socket.IO. In the function, instantiate a new notification object with the contents including an icon:

然后创建一个displayStatus函数,该函数传递通过Socket.IO接收的数据。 在函数中,实例化一个新的通知对象,其内容包括一个图标:

function displayStatus(message) {var notification = new Notification('Nexmo', {body: message,icon: 'images/icon-nexmo.png'});}

The source code on GitHub includes the fallback, in case a user denied the permission.

GitHub上的源代码包括回退,以防用户拒绝该权限。

Awesome! Now you have finished building a web app that allows you to send SMS messages, get the result callback from server and display it as a native web notification!

太棒了! 现在,您已完成构建一个Web应用程序,该应用程序允许您发送SMS消息,从服务器获取结果回调并将其显示为本地Web通知!

参考资料 (References)

  • Nexmo - SMS API DocumentationNexmo- SMS API文档
  • Nexmo Node.js Tutorial - How to Send SMS Messages with Node.jsNexmo Node.js教程- 如何使用Node.js发送短信
  • Express - expressjs.com快递-expressjs.com
  • Socket.IO - socket.ioSocket.IO - socket.io
  • Fetch API - Using fetch on MDN提取API- 在MDN上使用提取
  • Web Notifications - Using the Notifications API on MDNWeb通知- 在MDN上使用Notifications API

Also read more open-web articles at my personal site, Girliemac.com :-)

还可以在我的个人网站Girliemac.com上开放式网络文章:-)

翻译自: https://scotch.io/tutorials/send-sms-from-the-browser-with-web-apis-node-and-nexmo

node api框架

node api框架_使用Web API,Node和Nexmo从浏览器发送SMS相关推荐

  1. 【ASP.NET Web API教程】2.3 与实体框架一起使用Web API

    2.3 Using Web API with Entity Framework 2.3 与实体框架一起使用Web API 本小节是ASP.NET Web API第2章的第3小节,原文共分为7个部分,分 ...

  2. node mysql框架_关于nodejs的框架选择

    对于新入门的小伙伴来说,选择一个合适的nodejs框架可能是一件很头疼的事情,我最初也为这个头疼过,下面分享一下我的框架选择之路 nodejs的框架 最近来node的火热,带动了一大批的框架,例如 e ...

  3. python rest api 框架_Python Eve REST API框架

    说到Eve它是一款Python REST API框架,主要用于发布高可定制全功能的Web服务,可以上我们轻松创建部署Api. python eve现在的最新版本是0.1.0版本,它是一个开源项目遵循B ...

  4. python如何对接api接口_Python做Web API对接---查看接口

    3:Cookies(用户验证,基于HTTP协议的)之前的文章已经说了如何通过API登录验证,这里就不多说了,需要看的话,点击链接查看即可:https://club.kingdee.com/forum. ...

  5. webapi 路由限制命名控件_解决Web API路由配置支持Area及命名空间参数

    usingSystem;usingSystem.Collections.Concurrent;usingSystem.Collections.Generic;usingSystem.Linq;usin ...

  6. jenkins api使用_使用管理API和Jenkins作为IBM App Connect Professional部署自动化的持续集成引擎

    在本教程中,您将了解使用IBM App Connect Management API,SoapUI客户端和Jenkins在IBM App Connect(以前称为WebSphere®CastIron® ...

  7. 亚马逊 开发者api 调用_关于微信API:常用微信API文档整理

    微信公众平台消息接口为开发者提供了一种新的消息处理方式.微信公众平台消息接口为开发者提供与用户进行消息交互的能力.对于成功接入消息接口的微信公众账号,当用户发消息给公众号,微信公众平台服务器会使用HT ...

  8. kafka java api 删除_使用Java API创建(create),查看(describe),列举(list),删除(delete)Kafka主题(Topic)...

    使用Kafka的同学都知道,我们每次创建Kafka主题(Topic)的时候可以指定分区数和副本数等信息,如果将这些属性配置到server.properties文件中,以后调用Java API生成的主题 ...

  9. api质量等级_润滑油的API等级分类新

    柴油机油质量等级分类 一. 柴油机油的分类: API (美国石油学会) 将汽车发动机油分为 S - 汽油机油, C - 柴油机油. C 的 含义是 Commercial ,服务: Compressio ...

最新文章

  1. 关于Exchange Server 2010中OWA页面无法打开问题处理方法
  2. 微星主板超频_微星垄断AMD、Intel平台内存超频记录 ITX小板惊人
  3. OpenGL HDR色调映射的实例
  4. Mysql数据库(三)——mysql数据库高级操作
  5. 锐捷多网卡解决方案 与当前环境冲突(Code 2)
  6. Android安全笔记-Activity基本概念
  7. Confluence 6 示例 - https://confluence.atlassian.com/
  8. DHTML【10】--Javascript
  9. es6 箭头函数后面的大括号
  10. 从零开始学Symbian (基于carbid.c++、S60第三版)
  11. 互动媒体技术专题2——多视角认识十二个“一” 技术预演与方案设计
  12. MFC选择文件和文件夹对话框
  13. 说说数据一致性有哪几种?
  14. 40行Python代码利用DOI下载英文论文(2022.3.7)
  15. java瀑布图表,瀑布图的完美解决方案 [Excel图表]
  16. Primary主类和Catagory分类都存在相同事件
  17. 数据分析-思维分析逻辑day02
  18. 中国计算机专业的大学生相比于美国差在哪里?
  19. 人造金刚石 量子计算机,金刚石并非坚不可摧:科研小组创造首个量子计算机桥...
  20. 阀门定位器常见的六大故障

热门文章

  1. CAD快捷键小结(一)
  2. bootstrap treeview 无限子级菜单展示与JSON处理 完整
  3. 1138:破解简单密码
  4. 【MPI编程】矩阵向量乘法--解法二(高性能计算)
  5. 数据库设计3个泛式和经验谈
  6. Java 习题 (12)
  7. 第二章-数据描述(初级统计)
  8. Pycharm报错:FutureWarning: `distplot` is a deprecated function and will be removed in a future version
  9. 解释程序与解释程序的缺点,图解——解释程序与编译程序的区别
  10. 3年过去了!翟天临的微博又被写论文的研究生们喷了个底朝天...