我对AWS LAmbda有点新意,并试图通过AWS Lambda函数向服务器发出http请求。我使用了AWS HTTPS蓝图代码,只对option
变量进行了修改(参见下面的代码)。
const https = require('https');
let headers = {
'Authorization': 'ApiKey {key}'
};
let options = {
url: 'https://myds.io/api/external/patients/events/medications/',
headers: headers
};
exports.handler = (event, context, callback) => {
const req = https.request(options, (res) => {
let body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
callback(null, body);
});
});
req.on('error', callback);
req.write(JSON.stringify(event.data));
req.end();
};
当我尝试运行此代码时,我收到以下错误。我无法理解,问题出在哪里以及语法有什么问题。请你帮我。
只需调用此Lambda函数。我正在使用以下测试功能。
以下是执行结果。
Response:
{
"errorMessage": "connect ECONNREFUSED 127.0.0.1:443",
"errorType": "Error",
"stackTrace": [
"Object._errnoException (util.js:1022:11)",
"_exceptionWithHostPort (util.js:1044:20)",
"TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)"
]
}
Request ID:
"0fae1df6-6351-11e8-9741-a3dc748f359b"
Function Logs:
START RequestId: 0fae1df6-6351-11e8-9741-a3dc748f359b Version: $LATEST
2018-05-29T15:00:44.205Z 0fae1df6-6351-11e8-9741-a3dc748f359b {"errorMessage":"connect ECONNREFUSED 127.0.0.1:443","errorType":"Error","stackTrace":["Object._errnoException (util.js:1022:11)","_exceptionWithHostPort (util.js:1044:20)","TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)"]}
END RequestId: 0fae1df6-6351-11e8-9741-a3dc748f359b
REPORT RequestId: 0fae1df6-6351-11e8-9741-a3dc748f359b Duration: 35.27 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB
答案 0 :(得分:0)
在req.write(JSON.stringify(event.data));
正在搜索event.data
,但您的测试事件没有data
密钥,只有key1, key2, key3
。
尝试将测试事件更改为类似以下内容:
{
"data": "something"
}
答案 1 :(得分:0)
问题现在解决了。我已经在语法上做了一些编辑,它现在工作正常。
'use strict'
const https = require('https');
let options = {
host : 'myds.io',
path: '/api/external/patients/events/medications/',
headers: {
'Authorization': 'ApiKey *******'
},
};
exports.handler = (event, context, callback) => {
const req = https.request(options, (res) => {
let body = '';
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
// If we know it's JSON, parse it
if (res.headers['content-type'] === 'application/json') {
body = JSON.parse(body);
}
callback(null, body);
});
});
req.on('error', callback);
req.write(JSON.stringify(event.data));
req.end();
};