Reputation: 887
I have a component (code below) which sends a text message (sms), via Twilio, to a user when activated. The number being sent the text message is dynamic based on the user that's logged in at the time, so I need the number to be transmitted via the fecth post request. Once posted, I have a route (service) set on express to begin execution of the code to send the sms to the number.
My issue is that I can not seem to get access to the number that's been posted. How can I go about gaining accessing to the data being sent using the code below (If im even going about it the right way)?
Component:
//Fetch Request
var request = new Request('./time', {
method: 'POST',
body:'6626****'
});
getTime(){
fetch(request).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);});
});
}
Express Route (Service):
app.post("/time",function(req,res){
client.messages.create({
to: '+1'+req.data,
from: '+166****',
body: "This is the ship that made the Kessel Run in fourteen parsecs?
});
});
Upvotes: 1
Views: 76
Reputation: 73029
Twilio developer evangelist here.
cwbutler is definitely on the right track here. It would be better to send the data to your backend as a parameter in the post data and then use body parser to extract it. So, that would look a little like this.
First, use a parameter in the body and set the content type to application/x-www-form-urlencoded
.
var request = new Request('./time', {
method: 'POST',
body:'number=6626****',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
Then, install body-parser to your project.
$ npm install body-parser --save
Then in the Express app require body-parser, set the app to use it and look for the object req.body
which has your incoming parameter.
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded());
app.post("/time",function(req,res){
client.messages.create({
to: '+1'+req.body.number,
from: '+166****',
body: "This is the ship that made the Kessel Run in fourteen parsecs?"
});
});
Let me know if this helps at all.
Upvotes: 0
Reputation: 1260
You need to parse the body of post requests in express.
They have a middleware that you can install via npm that does this for you:
https://github.com/expressjs/body-parser
Upvotes: 1