【问题标题】:How to add JSON data in a http post request in AWS lambda?如何在 AWS lambda 的 http post 请求中添加 JSON 数据?
【发布时间】:2019-05-02 12:34:54
【问题描述】:
const http = require('http');

exports.handler = function(event, context) {
   var url = event && event.url;
    http.post(url, function(res) {
    context.succeed();
  }).on('error', function(e) {
    context.done(null, 'FAILURE');
  });

};

我在我的 AWS lambda 代码中使用它来发送 http 请求。

我有一个 JSON 文件,必须作为此发布请求的一部分发送。 如何添加 JSON ?我在哪里指定?

【问题讨论】:

  • http.post(url,, function(res) {})

标签: node.js http aws-lambda http-post


【解决方案1】:

如果您询问从哪里获取该 json 文件表单,那么 s3 将是放置该文件并从 lambda 读取并发布帖子的正确位置。

const obj= {'msg': [
{
  "firstName": "test",
  "lastName": "user1"
},
{
  "firstName": "test",
  "lastName": "user2"
}
]};

request.post({
  url: 'your website.com',
  body: obj,
  json: true
}, function(error, response, body){
console.log(body);
});

只需http

const postData = querystring.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

【讨论】:

  • 我试图在不使用请求且仅使用 http 的情况下做到这一点。
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2015-10-27
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多