我正在尝试从使用的示例服务(即 TripPin)中的 OData RESTful API 发布数据。请求成功,但响应 est 为空。在 AWS Lambda 平台中是否有任何特定的结构需要遵守以发出 HTTP post 请求?
var querystring = require('querystring');
var http = require('http');
exports.handler = function (event, context) {
var post_data = querystring.stringify(
{
UserName:'lewisblack',
FirstName:'Lewis',
LastName:'Black',
Emails:[
'[email protected]'
],
AddressInfo:[
{
Address: '187 Suffolk Ln.',
City: {
CountryRegion: 'United States',
Name: 'Boise',
Region: 'ID'
}
}
],
Gender: 'Male'
}
);
// An object of options to indicate where to post to
var post_options = {
host: event.url,
port: '80',
path: event.path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
console.log("hello");
context.succeed();
});
res.on('error', function (e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
});
// post the data
post_req.write(post_data);
post_req.end();
}
调用参数示例:
{
"url": "services.odata.org",
"path": "/v4/TripPinServiceRW/"
}
响应:空
请求 ID:“6f1ec2b4-5195-477f-9fb8-56fd33dee0ce”
函数日志:START RequestId:6f1ec2b4-5195-477f-9fb8-56fd33dee0ce 版本:$LATEST
结束请求enter code here
ID :6f1ec2b4-5195-477f -9fb8-56fd33dee0ce
报告请求 ID:6f1ec2b4-5195-477f-9fb8-56fd33dee0ce 持续时间:431.87 毫秒
计费持续时间:500 毫秒内存大小:128 MB 已用最大内存:73 MB
TL; 博士; 我认为您的 AWS Lambda 集成已损坏,但我很难确定。为讲座道歉。
我推荐以下内容:
您在event
对象中获得的内容取决于您调用 AWS Lambda 函数的方式。您可以通过 API 调用直接调用它,也可以通过让另一个 AWS 服务触发它来间接调用它。注意:
事件文档的结构因事件类型而异,并包含有关触发该功能的资源或请求的数据
https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html
找出问题的最简单方法可能是在处理程序的开头添加一些日志记录:
console.log(JSON.stringify(event));
一旦你弄清楚event
对象中的实际内容,就为它编写一个测试。这应该会改进您的代码设计和您的开发周期。
针对本地测试服务器测试上面的代码给出了成功的响应。见下文。
但这并不意味着它适用于https://services.odata.org。
同样,您应该弄清楚应该如何调用该服务并为其编写测试。
index.spec.js
var index = require("./index");
describe('index', () => {
it('can make requests to localhost', (done) => {
return index.handler({
"url": "localhost",
"path": "/"
}, {
done: done,
succeed: done
});
});
});
包.json
...
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^24.8.0"
}
...
输出:
> npm test
> [email protected] test /somepath/index.spec.js
> jest
PASS ./index.spec.js
index
✓ can make requests to localhost (20ms)
console.log index.js:44
Response: <html><body><h1>POST!</h1></body></html>
console.log index.js:45
hello
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.89s, estimated 1s
Ran all test suites.
您正在使用低级节点 http 库。像axios 这样的库可能会在短期内让你的生活更轻松。请参阅自述文件/维基上的 HTTP Post 示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句