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

如何解决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();
        });
        
    },};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?