使用 Axios/NodeJS API 调用函数的响应作为参数进行另一个 API 调用

Using the response of a Axios/NodeJS API call function as a parameter to make another API call

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

我已经调用了第一个端点并通过响应,我 return 一个对象,其格式是第二个端点需要的参数。

问题:我一直收到“转换后的数据必须是字符串、ArrayBuffer、缓冲区或流”

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

代码:


这个 return 是我需要在第二个 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}

如果我 post 来自第一个 API 调用的 return 作为参数,则此 return 是产品详细信息:

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

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

如果我没理解错,你只需要改一下

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

至此

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

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

的 return 值