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

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

问题描述

我不确定这是怎么回事,但是下面的我在节点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

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.html http://docs.aws.amazon. com/lambda/latest/dg/nodejs-create-deployment-pkg.html

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

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