Axios를 사용한 Alexa API 호출

17111 단어 nodeawsjavascript
Axios 라이브러리를 사용하여 Alexa를 통해 API 호출을 수행하는 방법을 살펴보겠습니다. 이것은 다른 라이브러리나 내장 가져오기 API를 사용하여 수행할 수 있지만.

Axios는 브라우저와 노드 모두에서 작동하는 약속 기반 HTTP 클라이언트입니다. JS 환경.
XMLHttpRequests 및 노드의 http 인터페이스를 처리하기 위한 단일 API를 제공합니다.

먼저 함수를 호출하려면 Intent가 필요합니다. FetchJokesIntent라고 부르겠습니다. 아마존 개발자 콘솔에서 추가될 것입니다. 예제를 최대한 간단하게 만들기 위해 "농담을 원합니다"라는 발화 하나를 추가하겠습니다. 😊




ko-US.json:



{
  "name": "FetchJokesIntent",
  "slots": [],
  "samples": [
    "i want a joke"
  ]
}


API 도우미 기능을 보자. 그 전에 package.json 파일에 Axios 종속성이 추가됩니다.


패키지.json:



"dependencies": {
  "ask-sdk-core": "^2.6.0",
  "ask-sdk-model": "^1.18.0",
  "aws-sdk": "^2.326.0",
  "axios": "^0.21.1"
}




logic.js:



const axios = require('axios');

module.exports.fetchJokesApi = async function fetchJokesApi() {
    let endpoint = 'http://api.icndb.com';
    let url = endpoint + '/jokes/random';

    let config = {
        timeout: 6500
    }

    try {
        let response = await axios.get(url, config);
        return  response.data;
    } catch (error) {
        console.log('ERROR', error);
        return null;
    }
}


API 응답을 기록하고 CloudWatch에서 로그를 볼 수 있습니다(Amazon CloudWatch는 모니터링 및 관리 서비스임). 다음은 응답 데이터의 예입니다.


의도는 사용자의 음성 요청을 이행하는 작업을 나타냅니다.
API를 호출하는 인텐트 기능:


index.js:



const FetchJokesHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'FetchJokesIntent';
    },
    async handle(handlerInput) {
        let response = await logic.fetchJokesApi();
        let speakOutput = response.value.joke;

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .getResponse();
    }
};


결과 😁





이제 함수를 좀 더 흥미롭게 만들기 위해 더 많은 API 필터와 사용자가 입력할 수 있는 음성 입력을 사용해 봅시다. 사전 정의된 슬롯 값 AMAZON.SearchQuery(고객이 정보를 검색할 때 사용할 수 있는 단어 및 구문에 사용합니다. 단문 메시지, 댓글, 검색 쿼리 및 기타 짧은 자유 형식 텍스트를 통합하는 기술은 이제 이 구문 슬롯을 활용할 수 있습니다.)

먼저 발화와 해당 유형의 슬롯을 추가해 보겠습니다.




ko-US.json:



{
  "name": "FetchJokesIntent",
  "slots": [
    {
      "name": "UserInput",
      "type": "AMAZON.SearchQuery"
    }
  ],
  "samples": [
    "I want a joke of {UserInput}",
    "i want a joke"
  ]
}


이제 코드는 다음과 같습니다. 슬롯 값을 가져오고 API에 매개변수로 전달될 두 단어(firstName 및 lastName)로 텍스트를 분할합니다.


index.js:



const FetchJokesHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'FetchJokesIntent';
    },
    async handle(handlerInput) {
        const slotValue = handlerInput.requestEnvelope.request.intent.slots.UserInput.value;
        let filterData = slotValue.split(" ");

        let response = await logic.fetchJokesApi(filterData[0], filterData[1]);
        let speakOutput = response.value.joke;

        return handlerInput.responseBuilder
            .speak(speakOutput)
            .getResponse();
    }
};




logic.js:



const axios = require('axios');

module.exports.fetchJokesApi = async function fetchJokesApi(first, last) {
    let endpoint = 'http://api.icndb.com';
    let resource = '/jokes/random';
    let filter = `?firstName=${first}&lastName=${last}`;
    let url = endpoint + resource + filter;

    let config = {
        timeout: 6500
    }

    try {
        let response = await axios.get(url, config);
        return  response.data;
    } catch (error) {
        console.log('ERROR', error);
        return null;
    }
}


이 문서가 API 요청을 만드는 데 도움이 되기를 바랍니다. 감사합니다 😊

좋은 웹페이지 즐겨찾기