带有请求的 AWS 节点 JS [英] AWS Node JS with Request

查看:25
本文介绍了带有请求的 AWS 节点 JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这里有什么问题,但我在 node js 下面的 lambda 不起作用

I am not sure whats wrong here but my lambda below in node js doesnt work

'use strict';
exports.handler = function (event, context) {
    try {

    var req = require('request');
    var headers = { 'User-Agent': 'Super Agent/0.0.1' };

    var options = {
        url: 'http://google.com',
        method: 'GET',
        headers: headers
    };

    req(options, function (error, response, body) {
        console.log(body);
    });

以上正确加载了模块,但由于某种原因它没有到达console.log(body).有人有想法吗?

The above is loading the module properly but it doesn't get to the console.log(body) for some reason. Anyone have an idea?

推荐答案

我假设您发布的代码就是您为 lambda 编写的代码.AWS Lambda 具有称为处理程序的特定入口点/函数,它在调用 lambda 时运行.所以每个 lambda 函数都必须有这个方法才能成为 lambda.

I am assuming that the code you posted is the code you wrote for lambda. AWS Lambda has specific entry point/function called handler which is runs when lambda is invoked. So every lambda function must have this method to qualify as lambda.

exports.handler = (event, context, callback) => {
}

也不会自动拉取 lambda 的外部依赖项.因此,我们需要使用依赖项压缩整个代码并将其上传到 lambda 以使其在有外部依赖项的情况下工作.

Also external dependencies of lambda is not automatically pulled. Hence, we need to zip the entire code with dependencies and upload it to lambda for it to work in case we have external dependency.

示例

lambda.js

var req = require('request');
var headers = { 'User-Agent': 'Super Agent/0.0.1' };

// Configure the request
var options = {
    url: 'http://google.com',
    method: 'GET',
    headers: headers
};

exports.handler = (event, context, callback) => {
 req(options, function (error, response, body) {
    console.log(body);
    callback(error);
 });
}

现在让我们考虑您的目录结构为

Now let us consider your directory structure to be as

node_modules/
lambda.js
package.json

现在您需要压缩此内容并将其上传到 AWS 中的 lambda.下一步是将 lambda.js 指向当前 lambda 的处理程序.

Now you need to zip this content and upload it to lambda in AWS. Next thing is to point the lambda.js as handler for the present lambda.

如果一切正常,您现在可以在调用 lambda 后看到 cloudwatch 中的日志.

If everything is done correctly, you can see now the log in cloudwatch after the lambda is invoked.

参考文献:

http://docs.aws.amazon.com/lambda/latest/dg/get-started-create-function.htmlhttp://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html

这篇关于带有请求的 AWS 节点 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆