Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - AWS Lambda HTTP POST Request (Node.js)

I'm relatively new to AWS lambda function and nodejs. I'm working on to try and get the list of 5 cities in a country by using HTTP POST request from this website: "http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry"

I've been searching about how to do a HTTP POST request in lambda function but I can't seem to find a good explanation for it.

Searches that I found for http post:

https://www.npmjs.com/package/http-post How to make an HTTP POST request in node.js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think that the cleaner and more performant way, without the need for externals libs can be something like this:

const https = require('https');

const doPostRequest = () => {

  const data = {
    value1: 1,
    value2: 2,
  };

  return new Promise((resolve, reject) => {
    const options = {
      host: 'www.example.com',
      path: '/post/example/action',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    //create the request object with the callback with the result
    const req = https.request(options, (res) => {
      resolve(JSON.stringify(res.statusCode));
    });

    // handle the possible errors
    req.on('error', (e) => {
      reject(e.message);
    });
    
    //do the request
    req.write(JSON.stringify(data));

    //finish the request
    req.end();
  });
};


exports.handler = async (event) => {
  await doPostRequest()
    .then(result => console.log(`Status code: ${result}`))
    .catch(err => console.error(`Error doing the request for the event: ${JSON.stringify(event)} => ${err}`));
};

This lambda has been made and tested on the following Runtimes: Node.js 8.10 and Node.js 10.x and is able to do HTTPS requests, to do HTTP requests you need to import and change the object to http:

const http = require('http');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...