javascript - 将请求库导入 node.js 上的 AWS Lambda

标签 javascript node.js aws-lambda

我用 const request = require("request") 调用请求库

enter image description here

我在 package.json 中添加了依赖项,我在下面发布了错误。
然而,通过阅读其他帖子,我意识到我可能需要 npm-install 请求模块并将整个 zip 作为文件夹导入。

由于我是 Node 新手,我想检查是否有另一种方法可以将“require”库导入当前工作目录,还是我在其他地方犯了错误?

这是我的 package.json:

{
  "name": "fact",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ask-sdk-core": "^2.0.0",
    "ask-sdk-model": "^1.0.0",
    "i18next": "^15.0.5",
     "request": "^2.88.0"
  }
}

当我测试时它仍然给我以下错误:
Response:
{
  "errorType": "Runtime.ImportModuleError",
  "errorMessage": "Error: Cannot find module 'request'",
  "trace": [
    "Runtime.ImportModuleError: Error: Cannot find module 'request'",
    "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
    "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
    "    at Object.<anonymous> (/var/runtime/index.js:45:30)",
    "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
    "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
    "    at Module.load (internal/modules/cjs/loader.js:653:32)",
    "    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
    "    at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
    "    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
    "    at startup (internal/bootstrap/node.js:283:19)"
  ]
}

Request ID:
"01b4df3d-e269-4d8a-90a3-7f02b9be9b58"

Function Logs:
START RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58 Version: $LATEST
2020-04-03T18:02:05.453Z    undefined   ERROR   Uncaught Exception  {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'request'","stack":["Runtime.ImportModuleError: Error: Cannot find module 'request'","    at _loadUserApp (/var/runtime/UserFunction.js:100:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:45:30)","    at Module._compile (internal/modules/cjs/loader.js:778:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)","    at Module.load (internal/modules/cjs/loader.js:653:32)","    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)","    at Function.Module._load (internal/modules/cjs/loader.js:585:3)","    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)","    at startup (internal/bootstrap/node.js:283:19)"]}
END RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58
REPORT RequestId: 01b4df3d-e269-4d8a-90a3-7f02b9be9b58  Duration: 2159.04 ms    Billed Duration: 2200 ms    Memory Size: 128 MB Max Memory Used: 19 MB  
Unknown application error occurred
Runtime.ImportModuleError

这是我使用请求的位置:
对于上下文,它是 Alexa 请求的事件处理程序。
const checkprof_Handler =  {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'IntentRequest' && request.intent.name === 'checkprof' ;
    },
    handle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        const responseBuilder = handlerInput.responseBuilder;
        let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

        let say = 'Let me check. ';

        let slotStatus = '';
        let resolvedSlot;

        let slotValues = getSlotValues(request.intent.slots); 


        // getSlotValues returns .heardAs, .resolved, and .isValidated for each slot, according to request slot status codes ER_SUCCESS_MATCH, ER_SUCCESS_NO_MATCH, or traditional simple request slot without resolutions

        // console.log('***** slotValues: ' +  JSON.stringify(slotValues, null, 2));
        //   SLOT: name 
        if (slotValues.name.heardAs) {
            slotStatus += ' slot name was heard as ' + slotValues.name.heardAs + '. ';

            var name = slotValues.name.heardAs;
            const url = `http://bluetooth-env-test.eba-brqgvwur.us-east-2.elasticbeanstalk.com/WebApp/search.php/
            ${name}`;

            request.get(url, (error, response, body) => {
            let json = JSON.parse(body);
            console.log('error:', error); // Print the error if one occurred
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
            console.log('body:', body); // Print the body

            // const theFact = body;                  
            // const speechOutput = theFact;
            // this.response.cardRenderer(SKILL_NAME, theFact);
            // this.response.speak(speechOutput + " Would you like another fact?").listen("Would you like another fact?");
            // this.emit(':responseReady');
        });

            slotStatus +=  slotValues.name.heardAs ;
        } else {
            slotStatus += 'slot name is empty. ';
        }
        if (slotValues.name.ERstatus === 'ER_SUCCESS_MATCH') {
            slotStatus += 'a valid ';
            if(slotValues.name.resolved !== slotValues.name.heardAs) {
                slotStatus += 'synonym for ' + slotValues.name.resolved + '. '; 
                } else {
                slotStatus += 'match. '
            } // else {
                //
        }
        if (slotValues.name.ERstatus === 'ER_SUCCESS_NO_MATCH') {
            slotStatus += 'which did not match any slot value. ';
            console.log('***** consider adding "' + slotValues.name.heardAs + '" to the custom slot type used by slot name! '); 
        }

        if( (slotValues.name.ERstatus === 'ER_SUCCESS_NO_MATCH') ||  (!slotValues.name.heardAs) ) {
            slotStatus += 'A few valid values are, ' + sayArray(getExampleSlotValues('checkprof','name'), 'or');
        }

        say += slotStatus;


        return responseBuilder
            .speak(say)
            .reprompt('try again, ' + say)
            .getResponse();
    },
};

最佳答案

无需在 lambda 函数中创建 Node 模块文件夹。只需创建一个文件夹并在该安装中需要,即 npm install require 并将其添加到 lambda 函数中的层。欲了解更多信息,请参阅 https://www.freecodecamp.org/news/lambda-layers-2f80b9211318/

注意:使用适当的运行时,即所有可用版本的 nodejs

关于javascript - 将请求库导入 node.js 上的 AWS Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61017939/

相关文章:

javascript - Discord JS - 交互创建和消息创建

javascript - 从 Lambda@Edge 函数获取客户端请求域

go - 如何在 Go 中创建 AWS Lambda 来处理多个事件

javascript - 如何使用html5生成临时公钥

javascript - 在使用 dojo.extend 扩展的 Dojo 类上调用构造函数

javascript - 按下按钮时的 Ajax 功能

node.js - 在 Windows 10 上运行 Docker Node 容器时出错

node.js - sequelize 使用现有的外键创建新记录

amazon-web-services - AWS CloudFormation - RDS 实例准备就绪后创建表吗?

javascript - twemoji 不转换字符串