Shelly
Shelly

Reputation: 11

Incorrect http response or timeout using NodeJS request in lambda function when building Alexa skill

I am building a new skill and my lambda function need to call another API to get some song's information. My lambda function is attached.

My issue is, I can open the url through Web browser and got correct response, but when I test the Play intent in the AWS Lambda website, sometime I got timeout, sometime I got 200 code but incomplete body like this: {"r":0,"is_show_quick_start":0,"song":[]}, where the "song" should have context in it. (you could see it if you open the url through any web browser)

Also, I test another url, which can also open through web browser, but always got 500 when I test it on the AWS Lambda website.

I'm very new to NodeJS and building Alexa skills. Could anyone please help me figure out? Thanks!

'use strict';

var Alexa = require('alexa-sdk');
var request = require('request');
var constants = require('./constants');

exports.handler = function(event, context, callback){
    var alexa = Alexa.handler(event, context, callback);
    alexa.registerHandlers(stateHandlers.startModeIntentHandlers);
    alexa.execute();
};

var stateHandlers = {
    startModeIntentHandlers : Alexa.CreateStateHandler(constants.states.START_MODE, {
        "LaunchRequest": function () {
            this.emit(':ask', 'Welcome to Douban FM');
        },

        "Play": function() {
            request.get(url.playlistUrl, function (error, response, body) {
                console.log('error:', error);
                console.log('statusCode:', response && response.statusCode);
                console.log('body:', body);
                // var d = JSON.parse(data);
                // var result = d.song.get(0).url;
                // console.log('result url:', result);
            });
            this.emit(':tell', "Ok.");
        }
    })
};

var url = {
    playlistUrl : 'https://douban.fm/j/mine/playlist?type=n&sid=966135&pt=206.8&channel=1&pb=64&from=mainsite&r=1d56c92354'
};

Upvotes: 1

Views: 491

Answers (1)

Vijayanath Viswanathan
Vijayanath Viswanathan

Reputation: 8541

Please try use 'https' package instead to call GET. Please see sample below,

function findSongIfo(callBack) {
var url = 'https://douban.fm/j/mine/playlist?type=n&sid=966135&pt=206.8&channel=1&pb=64&from=mainsite&r=1d56c92354';

var req = https.get(url, (res) => {
    var body = "";

    res.on("data", (chunk) => {
        body += chunk
    });

    res.on("end", () => {
        var result = JSON.parse(body);

        callBack(result)
    });
}).on("error", (error) => {
    callBack(err);
});
}
}

I have created that GET calls as a separate function, where you can pass the callback. You need to add below reference for 'http'package,

var https = require('https');

Upvotes: 1

Related Questions