维基百科的 API 无法在使用请求模块的 Alexa 技能中工作

Wikipedia's API not working in Alexa skill using Request module

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。其他 APIs 也不起作用。我需要使用 HTTP API 吗?我已经尝试了一切,但似乎没有任何效果。

我安装了请求依赖。

我只想让 Alexa return 地址的第一段。

您得到 Undefined,因为 没有值 分配 到变量 data. 因为在从 url.

获取数据之前,您的函数正在 returning

将 return 语句放入请求块中。还要从 obj 对象中提取要 return 的 属性。

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();
 }
};

使用您提供的 url 以下是您应该期望的响应:

{
     "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 CA5 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',
            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);
            return handlerInput.responseBuilder
            .speak(obj.query.pages["1928349"].extract)
            .getResponse();

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

这是JSON输出 { “body”:{ “版本”:“1.0”, “回复”: {}, "userAgent": "ask-node/2.9.0 Node/v10.22.1 sample/wiki-app/v1.0", “会话属性”:{} } }

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

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();
    }
};

此代码有效,这意味着我的 getinfointenthandler 确实有效。

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);
            return handlerInput.responseBuilder
            .speak(obj.query.pages["1928349"].extract)
            .getResponse();
        });
        
    },
    
};

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

这是我的JSON输入

"request": {
        "type": "SessionEndedRequest",
        "requestId": "amzn1.echo-api.request.f26816fa-672b-4e35-9de2-126780cfb1ef",
        "timestamp": "2020-10-05T20:52:16Z",
        "locale": "en-US",
        "reason": "ERROR",
        "error": {
            "type": "INVALID_RESPONSE",
            "message": "SpeechletResponse was null"
        }
    }
}