0

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 .

gouder hicham
  • 123
  • 10

2 Answers2

2

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.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • thank you sooo mich it worked so fine i did the post method but got an error i didn't know what's wrong but your solution worked with no problems thanks man . – gouder hicham Aug 02 '21 at 02:32
  • Awesome! If it did help, would you mind marking the answer as correct so that others can see it helped too. Thanks! – philnash Aug 02 '21 at 07:11
  • yes you did help , and i gave it an upvote , thanks ! – gouder hicham Aug 02 '21 at 14:35
  • @gouderhicham There's a tick next to the question that accepts it as the correct answer. It's a bit more definite than just an upvote and only the person who asked the question can accept the answer. – philnash Aug 02 '21 at 23:56
1

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()

LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • when i do post method is the express file and the index.js file with setting the body of msg to `body : req.body.msg` it say this error `POST http://localhost:3000/sendSms net::ERR_CONNECTION_RESET ` – gouder hicham Aug 01 '21 at 16:16