如何将 Alexa 请求处理程序引入另一个模块

How to bring the Alexa request handler in another module

我正在寻找如何将我的 Alexa 请求处理程序放入另一个模块的选项。这是我的方法:

  //index.js
  var Alexa = require('ask-sdk-core');
  var tests = require('./secondModule');

  var LaunchRequestHandler = tests('LaunchRequest','Hello, is this working?')

  var skillBuilder = Alexa.SkillBuilders.custom();

  exports.handler = skillBuilder
    .addRequestHandlers(
      LaunchRequestHandler
      )      
    .lambda();

我的第二个模块是这样的:

//secondModule.js
var Alexa = require('ask-sdk-core');

function Test(requestName, speechText){

    var request = requestName+"Handler"
    console.log("log: " +request)

    request = {
        canHandle(handlerInput) {
            console.log("log: "+request)
            return handlerInput.requestEnvelope.request.type === requestName;
        },
        handle(handlerInput) {

            return handlerInput.responseBuilder
                .speak(speechText)
                .reprompt(speechText)
                .withSimpleCard('Hello World', speechText)
                .getResponse();
        },
    };

}

module.exports = Test

但是如果我这样尝试,就会出现错误“"errorMessage": "Cannot read property 'canHandle' of undefined"”。你知道我该怎么做吗?我对 Node 很陌生,JavaScript

这是我的 package.json:

  {
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "actions-on-google": "^2.5.0",
    "ask-sdk-core": "^2.0.0",
    "ask-sdk-model": "^1.0.0"
  }
}

您不会退回 request。将您的 Test 函数更改为:

function Test(requestName, speechText){

  var request = requestName+"Handler"
  console.log("log: " +request)

  return request = {
    canHandle(handlerInput) {
      console.log("log: "+request)
      return handlerInput.requestEnvelope.request.type === requestName;
    },
    handle(handlerInput) {

      return handlerInput.responseBuilder
            .speak(speechText)
            .reprompt(speechText)
            .withSimpleCard('Hello World', speechText)
            .getResponse();
    },
  };
}

现在应该可以了!