TypeError 在从 Lambda 函数调用 API 时发生。

huangapple go评论81阅读模式
英文:

TypError when calling an API from a lambda function

问题

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?

英文:

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?

答案1

得分: 1

Here is the translated code snippet:

你可以尝试将以下代码部分替换为安全的 URL 格式
```js
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,
};

你也可以尝试对整个 options 对象进行 JSON.stringify() 处理,但需要确保你的 API 能够接受 JSON 格式的数据。


<details>
<summary>英文:</summary>
You may try to replace:
```js
const ans = body.answer
const phon = body.phone
const options = {
hostname: &#39;app.xxx.xx&#39;,
path: &#39;/api/v1/send?user_id=24xxx&amp;api_key=3Yxxxx&amp;sender_id=dEMO&amp;to=&#39;+{phon}+&#39;&amp;message=Your%OTP%is%&#39;+{ans}+&#39;thanks&#39;,
method: &#39;POST&#39;,
port: 443,
};

By:

const { phone, answer } = body;
  
const options = {
  hostname: &#39;app.xxx.xx&#39;,
  path: encodeURI(`/api/v1/send?user_id=24xxx&amp;api_key=3Yxxxx&amp;sender_id=dEMO&amp;to=${phone}&amp;message=Your%OTP%is%${answer}thanks`),
  method: &#39;POST&#39;,
  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.

huangapple
  • 本文由 发表于 2023年1月3日 17:16:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/74991236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定