想要访问此站点并在我的 lamda 处理程序中接收 JSON 结果。这是我的代码。是否有一个在 node.js 中进行 http 调用的工作示例,我可以建模?
const TornadaWarningIntentHandler = {
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'TornadoWarningIntent';
},
handle(handlerInput) {
var speakOutput = 'The Tornado is located at 123 Main St, Oregon Wisconsin. The storm is 13 miles to your southwest moving northeast at 45 miles per hour. Say repeat or Continue..';
const request = require('request');
request.post('https://api.weather.gov/points/38.8894,-77.0352', { json: { key: 'value' } }, (error, res, body) => {
if (error) {
speakOutput = "there was error in API call"
.speak(speakOutput)
return;
}
});
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt('Say continue for details...')
.getResponse();
}
};
此代码只是转到通用处理程序,该处理程序表示它在执行我要求的操作时遇到困难。 这似乎是一个标准活动,我没有找到任何样板代码来实现。我是不是错过了什么?
如果您的意思只是发出请求并访问响应,我建议您使用“axios”而不是“请求”。例如:
const axios = require('axios');
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
或使用异步/等待:
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
取自 axios 文档:https://github.com/axios/axios