Axios를 사용한 Alexa API 호출
17111 단어 nodeawsjavascript
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 요청을 만드는 데 도움이 되기를 바랍니다. 감사합니다 😊
Reference
이 문제에 관하여(Axios를 사용한 Alexa API 호출), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/awedis/alexa-api-calls-using-axios-4ej1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)