0

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?

hewa
  • 43
  • 7
  • Does this answer your question? [TypeError: Request path contains unescaped characters, how can I fix this](https://stackoverflow.com/questions/31024779/typeerror-request-path-contains-unescaped-characters-how-can-i-fix-this) – derpirscher Jan 03 '23 at 09:29

1 Answers1

1

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.

Paul-Marie
  • 874
  • 1
  • 6
  • 24
  • Thank you @Paul-Marie. If my API can consume JSON how to stringify the options object? and how can that increase the security? thanks. – hewa Jan 03 '23 at 13:12