将请求库导入到node.js上的AWS Lambda中

时间:2020-04-03 18:08:47

标签: 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();
    },
};

2 个答案:

答案 0 :(得分:3)

不需要在lambda函数中创建节点Module文件夹,只需创建一个文件夹并在其中进行安装即可,即npm install require并将其添加到lambda函数中的layer中。有关更多信息,请参见https://www.freecodecamp.org/news/lambda-layers-2f80b9211318/

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

答案 1 :(得分:1)

是的,您需要使用npm安装该库。 据我所知,您有两种简单的方法可以执行此操作,即使用aws cloud9或在您的本地环境中执行并将lambda上传到aws。

为了从您的本地环境中执行此操作,只需以zip格式下载功能,然后单击导出功能并选择“下载部署包”:

enter image description here

这将下载一个zip到您的本地环境,将其解压缩并放在文件夹内,打开终端并安装您的依赖项:

npm i request

再次压缩文件夹,然后使用aws-cli将其部署到aws:

aws lambda update-function-code --function-name=your_function_name --zip-file fileb://your_zip_file_name.zip