How to get a Twilio SMS body text in Node.js

旧时模样 提交于 2019-12-13 04:06:29

问题


I'm working on a side-project of mine which integrates with Twilio. It's a Node.js app running on the Hapi.js framework.

I have the app set up with Twilio so that when I text my Twilio number, Twilio gets the request from my app's route and texts me back with a static message in the response.

What I'm having trouble with is getting the SMS body from the user's text. Let's say that I text the Twilio number with a word like banana I want to be able to retrieve that from the request so that I can have a dynamic message based on it.

I've tried request.Body, request.message, among several other things, and I can't seem to retrieve the user's text to the Twilio number. I've looked through Twilio's documentation and can't seem to figure it out. I saw this PHP keyword tutorial on Twilio which looked promising, but even accessing request.Body as in that tutorial doesn't seem to work at all.

Does anyone know how to get the text body from a Twilio SMS that a user sends? Any and all help is appreciated


回答1:


With Hapi, if you want to read all the request body into memory before running your handler you need to set the payload config:

server.route({
    config: {
        payload: {
            output: 'data'
        }
    },
    method: 'POST',
    path: '/textMessage',
    handler: function (request, reply) {
        console.log('Body was', request.payload.toString()); 
        reply('...');
    }
});

From the Hapi API docs:

'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, the raw Buffer is returned. This is the default value except when a proxy handler is used.

More options here: http://hapijs.com/api#route-options




回答2:


After trying different methods to retrieve the request payload from Twilio, I found that the Twilio request body can be accessed via request.url.query, and therefore, the Body of the text, can be retrieved via request.url.query.Body. Thanks for the help @MattHarrison!



来源:https://stackoverflow.com/questions/28017970/how-to-get-a-twilio-sms-body-text-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!