h.zak
h.zak

Reputation: 1527

Serverless nodejs skip https request

I want to send a https request and process the result with serverless framework, but it seems not working.

Nodejs (serverless) skip my request and jump directly to the last result without waiting https reponse

here my function:

import { APIGatewayEvent, Callback, Context, Handler } from "aws-lambda";
var AWS = require("aws-sdk");
const querystring = require('querystring');
const https = require('https');

const TOKEN: String = "token";

export const hello: Handler = (
  event: APIGatewayEvent,
  context: Context,
  cb: Callback
) => {
function https_request() {

    var postData = querystring.stringify({
      query: "query"
    });

    var options = {
      hostname: 'example.com',
      port: 443,
      path: '/path',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': TOKEN
      }
    };


    return new Promise(function(resolve, reject) {
      console.log("before request")
      var req = https.request(options, (res) => {
        console.log('statusCode:', res.statusCode);
        console.log('headers:', res.headers);

        if (res.statusCode !== 200) {

          // REJECT IF THE RESPONSE WASN'T AS EXPECTED
          return reject(new Error('Request failed'));
        }

        res.on('data', (d) => {

          process.stdout.write(d);
          resolve(d); // RESOLVE ON SUCCESS WITH EXPECTED DATA

        });
      });

      req.on('error', (e) => {
        console.error(e);
        reject(e); // REJECT ON REQUEST ERROR
      });

      // req.write(postData);
      req.end();
    }) 

  }
  let x:any;



async function myAsyncF() {
    x= await https_request();
    console.log(x.body)
    return x.body
  }

  myAsyncF()

  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: x,
      input: event
    })
  };

  cb(null, response);
};

I used the async await, but nothing is returned (i should receive at least an error if there is some king of network error)

here is my output: before request { "statusCode": 200, "body": "{\"input\":\"\"}" }

is there something missing ?

Thank you in advance

Upvotes: 0

Views: 395

Answers (2)

GopiinSO
GopiinSO

Reputation: 11

Remove process.stdout.write will is not a great practice as you are running your code on lambda, use a context object or a callback function to return

process.stdout.write(d) is write operation on file, sometimes it silently fails as well, running on EC2, ECS your solution looks gem. But on serverless it's always better to avoid file operation functions

Upvotes: 0

James
James

Reputation: 82096

At no point do you resolve your Promise, I've no idea what you deem a "successful" request but here's an example that should get you on the right track

return new Promise(function(resolve, reject) {
  console.log("before request")
  var req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    if (res.statusCode !== 200) {
      // REJECT IF THE RESPONSE WASN'T AS EXPECTED
      return reject(new Error('Request failed'));
    }

    res.on('data', (d) => {
      process.stdout.write(d);
      resolve(d); // RESOLVE ON SUCCESS WITH EXPECTED DATA
    });
  });

  req.on('error', (e) => {
    console.error(e);
    reject(e); // REJECT ON REQUEST ERROR
  });

  req.write(postData);
  req.end();
})

Upvotes: 2

Related Questions