如何向存储在 JSON 文件中的号码发送短信?

问题描述

我需要将 SMS(通过 Twilio)发送到定义的电话号码,当点击提交按钮时,这些电话号码保存在 phone.json 文件中。

我正在使用 node.js

我该怎么做?

这是我的 phone.json 的样子:

[
 {"Nombre": "Nombre1","Numero": "+34...."
  },{"Nombre": "Nombre2","Numero": "+34..."
 }
]

在 SMS.js 中,我会创建一个这样的函数

function submit() {
  client.messages 
    .create({
      body: "content",from: "+....",to: ""}) //this number should come from phone.json
    .then(message => console.log(message.sid));
}

这是我的 index.js 的样子:

const http =require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const { fstat } = require('fs');
const { response } = require('express');
const info = require("./database.json"); 
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({extended: true}));

app.listen(8000,console.log(`Server running at http://localhost:8000`));

我会很高兴收到每一条建议。

解决方法

我假设您想在 Node.js 中执行此服务器端操作,那么您需要 fs 来读取 JSON,然后您只需像这样在 submit() 中循环遍历它:

import fs from "fs";  // CommonJS syntax: const fs = require("fs");
phone_numbers = JSON.parse(fs.readFileSync("phone.json","utf8"));
phone_numbers.forEach(function(item,index) {
  console.log(item,index);
  client.messages 
    .create({
      body: "content",from: "+....",to: item["Numero"],})
    .then(message => console.log(message.sid));
});