Returning XML in response from Loopback Remote Method

后端 未结 2 1327
遥遥无期
遥遥无期 2021-01-23 08:24

I am using the Loopback Connector REST (1.9.0) and have a remote method that returns XML:

   Foo.remoteMethod
   (  
      \"getXml\",
      {
         accepts:          


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-23 08:30

    I recently ran into this with trying to create a dynamic response for Twilio voice calling in Loopback 3.x. In the model.remoteMethod call, explicitly specify the return type and content type as follows:

    model.remoteMethod(
        "voiceResponse", {
            accepts: [{
                arg: 'envelopeId',
                type: 'number',
                required: true
            }],
            http: {
                path: '/speak/:envelopeId',
                "verb": 'post'
            },
            returns: [{
                arg: 'body',
                type: 'file',
                root: true
            }, {
                arg: 'Content-Type',
                type: 'string',
                http: {
                    target: 'header'
                }
            }],
    
        }
    )
    

    Have your method return both the xml and the content type via the callback function. Note that the first argument in the callback is to return an error if one exists:

    model.voiceResponse = function(messageEnvelopeId, callback) {
    
        app.models.messageEnvelope.findById(messageEnvelopeId, {
            include: ['messages']
        }).then(function(res) {
            let voiceResponse = new VoiceResponse();
            voiceResponse.say({
                    voice: 'woman',
                    language: 'en'
                },
                "This is a notification alert from your grow system. " + res.toJSON().messages.message
            )
    
            callback(null,
                voiceResponse.toString(), // returns xml document as a string
                'text/xml'
            );
        });
    }
    

提交回复
热议问题