Wikipedia的API无法使用Request模块以Alexa技能工作

问题描述

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

        let options = { method: 'GET',url :  "https://en.wikipedia.org/w/api.PHP?format=json&origin=*&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=manulife&redirects=",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;

        });
        const x = "Hello";
        const speechOutput = data;
        return handlerInput.responseBuilder
        .speak(speechOutput)
        .getResponse();
    },};

我得到的答复是Undefined。其他API也不起作用。我需要使用HTTP API吗?我已经尝试了一切,但似乎没有任何效果

我已安装请求依赖项。

我只希望Alexa返回地址的第一段。

解决方法

您将得到Undefined,因为没有值分配到变量数据中。 因为您的函数在从url提取数据之前就返回了。

将return语句放入请求块中。另外,从obj对象中提取要返回的属性。

const request = require("request");
const getData = function() {
return new Promise((resolve,reject) => {
    let options = { 
        method: 'GET',url :  "https://en.wikipedia.org/w/api.php?format=json&origin=*&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles=manulife&redirects=",qs: {
            action: 'query' 
        } 
    };
    request(options,function (error,response,body) {
        if (error) reject(error);
        resolve(JSON.parse(body)); // you may want to check parsing error.
    });
 });
}
const HelloWorldIntentHandler = {
  canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 
       'IntentRequest'
        && Alexa.getIntentName(handlerInput.requestEnvelope) === 
       'HelloWorldIntent';
},async handle(handlerInput) {
    const response = await getData();
    console.log(response);
    return handlerInput.responseBuilder
    .speak(response.query.pages["1928349"].extract)
    .getResponse();
 }
};

使用您提供的网址是您应该得到的响应:

{
     "batchcomplete": "","query": {
     "normalized": [
        {
            "from": "manulife","to": "Manulife"
        }
      ],"pages": {
            "1928349": {
            "pageid": 1928349,"ns": 0,"title": "Manulife","extract": "Manulife Financial Corporation (also known as Financière 
                        Manuvie in Quebec) is a Canadian multinational insurance 
                        company and financial services provider headquartered in 
                        Toronto,Ontario,Canada. The company operates in Canada and 
                        Asia as \"Manulife\" and in the United States primarily 
                        through its John Hancock Financial division. As of December 
                        2015,the company employed approximately 34,000 people and had 
                        63,000 agents under contract,and has CA$935 billion in assets 
                        under management and administration. Manulife services over 26 
                        million customers worldwide.Manulife is the largest insurance 
                        company in Canada and the 28th largest fund manager in the 
                        world based on worldwide institutional assets under management 
                       (AUM).Manulife Bank of Canada is a wholly owned subsidiary of 
                        Manulife."
          }
        }
      },"limits": {
    "extracts": 20
  }
 }
,
const GetInfoIntentHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'GetInfoIntent');
    },handle(handlerInput) {
        let data;
        const request = require("request");

        let options = { method: 'GET',qs: 
            { action: 'query' } };

        request(options,body) {
            if (error) throw new Error(error);
            let json = body;
            let obj = JSON.parse(json);
            return handlerInput.responseBuilder
            .speak(obj.query.pages["1928349"].extract)
            .getResponse();

        });
        const x = "Hello";
        
    },};

这是JSON输出 { “身体”: { “ version”:“ 1.0”, “响应”:{}, “ userAgent”:“询问节点/2.9.0节点/v10.22.1样本/wiki-app/v1.0”, “ sessionAttributes”:{} } }

这是我的错误 “请求的技能的响应出现问题”

,
len_a = numpy.shape(a)[0]
sum_b = sum(b)
c = numpy.zeros((1,0))
for idx in range(len_a):
    repeated_a = numpy.repeat(a[idx],b[idx])
    repeated_a = numpy.reshape(repeated_a,(1,numpy.shape(repeated_a)[0]))
    c = numpy.hstack((c,repeated_a))

此代码有效,这意味着我的getinfointenthandler可以工作。

const GetInfoIntentHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'GetInfoIntent');
        
    },handle(handlerInput) {
        const speakOutput = 'reached intenthandler';

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

此代码无效。启动请求后它将停止。

这是我的JSON输入

const GetInfoIntentHandler = {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return (request.type === 'IntentRequest'
        && request.intent.name === 'GetInfoIntent');
        
    },handle(handlerInput) {
        let data;
        const request = require("request");
        let options = { method: 'GET',qs: 
        { action: 'query' } };
        request(options,body) {
            if (error) throw new Error(error);
            let json = body;
            let obj = JSON.parse(json);
            return handlerInput.responseBuilder
            .speak(obj.query.pages["1928349"].extract)
            .getResponse();
        });
        
    },};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...