gouder hicham
gouder hicham

Reputation: 133

how can i send custom sms message with twilio api via express

so im trying to make a simple function in a web that has input and button , and when i click the button twilio api send message with the body of input value life if input is hello the message sent is hello, this is the index.js file which is include the simple function that gonna send the message and i don't know if i should use POST method or get just look

let input = document.querySelector("input").value;
document.querySelector("button").addEventListener("click", whatTheHell);
let whatTheHell = () => {
  fetch("/sendSms")
    .then((res) => res.json())
    .then((res) => console.log(res))
    .catch((err) => console.log(err));
};

and this the express.js file that contain the twilio api that gonna send the sms

const express = require("express");
if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}
const accountSid = process.env.accountSid;
const authToken = process.env.authToken ; 
const app = express();
const client = require("twilio")(accountSid, authToken);
app.use(express.json());
app.use(express.static("public"));

app.get("/sendSms", (req, res) => {
  client.messages
    .create({
      body: "message from me",
      messagingServiceSid: "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      to: "NUMBER",
    })
    .then((message) => {
      res.json({ message: message }).done();
    });
});

app.listen(3000, () => {
  console.log("Server Started");
});

so what i want here in body: "message from me" is to be something like this body : user.input or something like that , i tried using post method and did req.body.msg and msg is input.value but it dont accept post method .

Upvotes: 0

Views: 837

Answers (2)

philnash
philnash

Reputation: 73075

Twilio developer evangelist here.

I would recommend making this a POST request. You need to update a few things to get your input from the front end to the server. Let's start with the front end.

Instead of getting the input's value straight away, you should wait until the button is clicked to get the value. Then, when it is clicked, you need to make a POST request with the message you want to send in the body of the request. One way to do that is to JSON stringify an object of data.

let input = document.querySelector("input");
document.querySelector("button").addEventListener("click", whatTheHell);
let whatTheHell = () => {
  const message = input.value;
  fetch("/sendSms", {
    method: "POST",
    body: JSON.stringify({ message: message }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then((res) => res.json())
    .then((res) => console.log(res))
    .catch((err) => console.log(err));
};

Now, on the server side we need to update your endpoint to receive POST requests. You are already using the express JSON parsing middleware, so the message will be available as req.body.message. We can then use that in the request to Twilio.

const express = require("express");
if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}
const accountSid = process.env.accountSid;
const authToken = process.env.authToken ; 
const app = express();
const client = require("twilio")(accountSid, authToken);
app.use(express.json());
app.use(express.static("public"));

app.post("/sendSms", (req, res) => {
  const message = req.body.message;
  client.messages
    .create({
      body: message,
      messagingServiceSid: "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      to: "NUMBER",
    })
    .then((message) => {
      res.json({ message: message });
    })
    .catch((error) => {
      console.error(error);
      res.status(500).json({ error: error.message });
    });
});

app.listen(3000, () => {
  console.log("Server Started");
});

And that should work.

Upvotes: 2

LeeLenalee
LeeLenalee

Reputation: 31431

You can use a query paramater to send the message to your express server and retrieve them in your server as explained here: How to get GET (query string) variables in Express.js on Node.js?.

If you make your method a post method when sending it you also need to make your express from get to post like so: app.get() -> app.post()

Upvotes: 1

Related Questions