NodeJS 如何在JSON中模拟等量

enyaitl3  于 2023-04-29  发布在  Node.js
关注(0)|答案(2)|浏览(120)

我正在尝试模拟一个REST API端点函数,我想在端点上检查交换货币
试 Postman
我做这个https://api.flutterwave.com/v3/transfers/rates?amount=1000&destination_currency=USD&source_currency=KES
此后,我输入我的密钥,我得到这个作为响应

{
    "status": "success",
    "message": "Transfer amount fetched",
    "data": {
        "rate": 140.556,
        "source": {
            "currency": "KES",
            "amount": 140556
        },
        "destination": {
            "currency": "USD",
            "amount": 1000
        }
    }
}

现在我想把它变成一个函数,我想得到上面显示的等价货币
看到我试图模拟的函数了吗

const GetEqCurrency = async (source_currency, destination_currency, amount) => {
  var header = {
    Accept: "application/json",
    "Content-type": "application/json",
    Authorization:
      "Bearer FLWSECK_TEST-153740d351951b5f6d5ae8b903e0c467-X",
  };

  var url = `https://api.flutterwave.com/v3/transfers/rates?amount=${amount}&destination_currency=${destination_currency}&source_currency=${source_currency}`;

  fetch(url, 
    { method: "GET", headers: header }).then((response) => response.json())
    .then((responseJson) =>{
      if(responseJson.message == 'Transfer amount fetched'){
        //console.log()
    
    // Help me output the equivalient data here in json
      }
    })
};

如何在json中输出以下值请在这里帮助我。

eufgjt7s

eufgjt7s1#

仅供参考-您可以使用Postman生成获取请求的示例片段。Have a look here
那么试试这个:

const GetEqCurrency = async (source_currency, destination_currency, amount) => {
  var header = {
    Accept: "application/json",
    "Content-type": "application/json",
    Authorization:
      "Bearer FLWSECK_TEST-153740d351951b5f6d5ae8b903e0c467-X",
  };

  var url = `https://api.flutterwave.com/v3/transfers/rates?amount=${amount}&destination_currency=${destination_currency}&source_currency=${source_currency}`;

  try {
    const response = await fetch(url, { method: "GET", headers: header });
    const responseJson = await response.json();
    if (responseJson.message == "Transfer amount fetched") {
      return responseJson.data;
    }
  } catch (error) {
    console.log(error);
  }
};
nmpmafwu

nmpmafwu2#

你需要return你需要从函数中得到的东西:

const GetEqCurrency = async (source_currency, destination_currency, amount) => {
  const headers = {
    Accept: "application/json",
    "Content-type": "application/json",
    Authorization:
      "Bearer FLWSECK_TEST-153740d351951b5f6d5ae8b903e0c467-X",
  };

  // saves you from composing the query string manually
  const params = new URLSearchParams({
    amount,
    destination_currency,
    source_currency,
  });  

  const url = `https://api.flutterwave.com/v3/transfers/rates?${params}`;
  const response = await fetch(url, { headers });
  const parsed = await response.json();

  if (parsed.message !== 'Transfer amount fetched') {
    // or better throw an appropriate exception
    return null;
  }
  // return what you need from the response
  return parsed.data.destination.amount;
};

相关问题