javascript 从lambda函数调用API时出现TypError

jvlzgdj9  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(126)

我需要从我的lambda函数调用一个API来发送一个OTP,为此,我需要为路径传递一些查询字符串,所以我如下所示。

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);
};

但是当我这样做时,我得到这个错误,'TypeError [ERR_UNESCAPED_CHARACTERS]:请求路径包含非转义字符'如何解决这个问题?

mi7gmzs6

mi7gmzs61#

您可以尝试替换:

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,
    
  };

签署人:

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,
};

你也可以尝试JSON.stringify()整个options对象,但它需要确保你的API可以使用JSON。

相关问题