如何将 superagent(或任何请求库)安装到无服务器框架 AWS Lambda 函数中?
How to install superagent (or any request library) into Serverless Framework AWS Lambda function?
我希望我的 lambda 函数能够发出网络请求。
这是我的提供商
provider:
name: aws
runtime: nodejs10.x
我在项目的根目录下有 package.json
和 node_modules
。
我正在像这样导入超级代理:const request = require('superagent')
。
但每当我尝试使用它时 (await request.post(url).send(body)
),它会抛出一个错误提示
ERROR ERR TypeError: Cannot read property 'request' of undefined
at Request.request
您不必使用任何外部库来发出 http/https 请求。
相反,您可以使用 nodejs http/https 模块。
这是一个 https 请求作为承诺的工作示例,灵感来自 Nodejs 文档中的示例(link 下面):
const https = require('https');
const requestPromise = (options, request_body= '') => {
return new Promise((resolve, reject) => {
let response_data;
const post_req = https.request(options, (res) => {
res.on('data', (chunk) => {
if (response_data) {
response_data += chunk;
} else {
response_data = chunk;
}
});
res.on('end', () => {
resolve(response_data);
});
});
// request error
post_req.on('error', (err) => {
reject(err);
});
// post data and end request
post_req.write(JSON.stringify(request_body));
post_req.end();
});
}
以下是您的使用方法:
const request_body = {
"data": "your data"
};
const request_options = {
host: host,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/json' // your headers
},
data: JSON.stringify(request_body)
};
const response = await requestPromise(request_options , request_body );
有关更多信息,请查看 Nodejs 文档:
https://nodejs.org/api/https.html#https_https_request_options_callback
我希望我的 lambda 函数能够发出网络请求。
这是我的提供商
provider:
name: aws
runtime: nodejs10.x
我在项目的根目录下有 package.json
和 node_modules
。
我正在像这样导入超级代理:const request = require('superagent')
。
但每当我尝试使用它时 (await request.post(url).send(body)
),它会抛出一个错误提示
ERROR ERR TypeError: Cannot read property 'request' of undefined
at Request.request
您不必使用任何外部库来发出 http/https 请求。 相反,您可以使用 nodejs http/https 模块。 这是一个 https 请求作为承诺的工作示例,灵感来自 Nodejs 文档中的示例(link 下面):
const https = require('https');
const requestPromise = (options, request_body= '') => {
return new Promise((resolve, reject) => {
let response_data;
const post_req = https.request(options, (res) => {
res.on('data', (chunk) => {
if (response_data) {
response_data += chunk;
} else {
response_data = chunk;
}
});
res.on('end', () => {
resolve(response_data);
});
});
// request error
post_req.on('error', (err) => {
reject(err);
});
// post data and end request
post_req.write(JSON.stringify(request_body));
post_req.end();
});
}
以下是您的使用方法:
const request_body = {
"data": "your data"
};
const request_options = {
host: host,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/json' // your headers
},
data: JSON.stringify(request_body)
};
const response = await requestPromise(request_options , request_body );
有关更多信息,请查看 Nodejs 文档: https://nodejs.org/api/https.html#https_https_request_options_callback