【问题标题】:Using the response of a Axios/NodeJS API call function as a parameter to make another API call使用 Axios/NodeJS API 调用函数的响应作为参数进行另一个 API 调用
【发布时间】:2022-02-16 04:04:42
【问题描述】:

一般概念:我正在访问两个 API 端点。一个回复一般信息,另一个回复具体信息。

我已经调用了第一个端点,并通过响应返回了一个对象,其格式为第二个端点作为参数所需的格式。

问题:我不断收到“转换后的数据必须是字符串、ArrayBuffer、Buffer 或 Stream”

我想学习跨控制器使用功能,以免自己重复。

代码:


这将返回我需要在第二个 API 调用中使用的对象:

const axios = require("axios");
const getSpecials = async (req, res) => {
  try {
    const response = await axios.get(`${apiURL}/categories`);
    let specials = [];
    let skus = [];
    response.data.forEach((element, index) => {
      if (response.data[index].is_special == true) {
        specials.push({
          name: response.data[index].name,
          product_skus: response.data[index].product_skus,
          _id: response.data[index]._id,
        });
        skus.push(response.data[index].product_skus);
      }
    });
    return { product_skus: skus.flat() };
  } catch (error) {
    console.log(error.message);
  }
};

module.exports = {getSpecials}

如果我将第一个 API 调用的返回作为参数发布,这将返回产品详细信息:

const axios = require("axios");
const { getSpecials } = require("./categoriesControllers");
const specialProducts = async (req, res) => {
  try {
    const response = await axios.post(`${apiURL}/products`, getSpecials);
    res.status(200).json(response.data);
  } catch (error) {
    console.log(error.message);
  }
};

任何关于如何最好地做到这一点的建议都会很棒。我想学会让后端完成所有繁重的工作,并且我想尽可能干净地将数据提供给前端。

【问题讨论】:

    标签: javascript node.js axios backend


    【解决方案1】:

    如果我理解正确,你只需要改变

    const response = await axios.post(`${apiURL}/products`, getSpecials);

    到这里

    const response = await axios.post(`${apiURL}/products`, await getSpecials());

    因为现在您将函数声明传递给 axios post 函数的第二个参数,而不是 getSpecials 的返回值

    【讨论】:

    • 你完全理解。信不信由你,我一直在网上寻找答案。我应该早点在这里问。谢谢瓦莱里。我学到了一些新东西。我还有很多东西要学。你是明星。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2021-01-06
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多