Home > other >  TypError when calling an API from a lambda function
TypError when calling an API from a lambda function

Time:01-04

I need to call an API from my lambda function to send an OTP and for that for the path I need to pass some query strings so I do as shown below.

const https = require('https');

function postRequest(body) {
  
  const ans = body.answer
  const phon = body.phone
  
  
  const options = {
    hostname: 'app.xxx.xx',
    path: '/api/v1/send?user_id=24xxx&api_key=3Yxxxx&sender_id=dEMO&to=' {phon} '&message=Your%OTP%is%' {ans} 'thanks',
    method: 'POST',
    port: 443,
    
  };

  return new Promise((resolve, reject) => {
    const req = https.request(options, res => {
      let rawData = '';

      res.on('data', chunk => {
        rawData  = chunk;
      });

      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData));
        } catch (err) {
          reject(new Error(err));
        }
      });
    });

    req.on('error', err => {
      reject(new Error(err));
    });

    
    req.write(JSON.stringify(body));
    req.end();
  });
}

exports.handler = async (event, context, callback) => {
  //Create a random number for otp
  const challengeAnswer = Math.random().toString(10).substr(2, 4);
  const phoneNumber = event.request.userAttributes.phone_number;

  console.log(event, context);
 
  await postRequest({
      phone: phoneNumber,
      answer: challengeAnswer,
    },
    function(err, data) {
      if (err) {
        console.log(err.stack);
        console.log(data);
        return;
      }
      console.log(`SMS sent to ${phoneNumber} and otp = ${challengeAnswer}`);
      return data;
    });

callback(null, event);
};

But when I do so I get this error, 'TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters' How to fix this?

CodePudding user response:

You may try to replace:

const ans = body.answer
  const phon = body.phone
  
  
  const options = {
    hostname: 'app.xxx.xx',
    path: '/api/v1/send?user_id=24xxx&api_key=3Yxxxx&sender_id=dEMO&to=' {phon} '&message=Your%OTP%is%' {ans} 'thanks',
    method: 'POST',
    port: 443,
    
  };

By:

const { phone, answer } = body;
  
const options = {
  hostname: 'app.xxx.xx',
  path: encodeURI(`/api/v1/send?user_id=24xxx&api_key=3Yxxxx&sender_id=dEMO&to=${phone}&message=Your%OTP%is%${answer}thanks`),
  method: 'POST',
  port: 443,
};

in order to have an url safe format. You may also try to JSON.stringify() the whole options object, but it will need to ensure your API can consume JSON.

  • Related