简体   繁体   English

Alexa-通过Lambda访问外部API

[英]Alexa - Accessing External API via Lambda

I am making an Alexa skill and need it to query an API, however it just simply doesnt seem to work and i have tried 1 million different ways. 我正在掌握Alexa技能,需要它来查询API,但是它似乎根本不起作用,我尝试了100万种不同的方法。 Would be great if someone could take a look at the code below and add a basic API query, thanks! 如果有人可以看一下下面的代码并添加基本的API查询,那就太好了,谢谢!

const playersOnlineHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'playersOnlineIntent');
    },
    handle(handlerInput) {
        const data =https.get("URL");
        const x = "Hello";
        const speechOutput = "There is currently" + data + "players online";
        return handlerInput.responseBuilder
        .speak(speechOutput)
        .getResponse();
    },
};

You can try this code for HTTP GET API calls 您可以尝试将此代码用于HTTP GET API调用

const playersOnlineHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'playersOnlineIntent');
    },
    handle(handlerInput) {
        let data;
        const request = require("request");

        let options = { method: 'GET',
            url: 'http://exaple.com/api.php',
            qs: 
            { action: 'query' } };

        request(options, function (error, response, body) {
            if (error) throw new Error(error);
            let json = body;
            let obj = JSON.parse(json);
            data = obj.element.value;

        });
        const x = "Hello";
        const speechOutput = "There is currently" + data + "players online";
        return handlerInput.responseBuilder
        .speak(speechOutput)
        .getResponse();
    },
};

You can refer to the following snippet. 您可以参考以下代码段。 Works well with https built-in module https内置模块配合使用

handle(handlerInput) {

  https.get('https://jsonplaceholder.typicode.com/todos/1', res => {
    res.setEncoding("utf8");
    let body = "";

    res.on("data", data => {
        body += data;
    });
    //On receiving the entire info from the API
    res.on("end", () => {
        body = JSON.parse(body);

        speechOutput += 'Sample Info' + body.userId;

        return handlerInput.responseBuilder
              .speak(speechOutput)
              .getResponse();

    });
  });
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM