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

Time:02-16

General concept: I am accessing two API endpoints. One responds with general information, and the other with specific information.

I have called the first endpoint and with the response, I return an object in the format that the second endpoint requires as a parameter.

Problem: I keep getting "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream"

I want to learn to use functions across controllers, so as not having to REPEAT myself.

Code:


This returns the object that I need to use in the second API call:

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}

This returns the product details if I post the return from the first API call as a parameter:

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

Any suggestions on how best to do this would be great. I want learn to let the backend to do all the heavy lifting and I want to serve the data as cleanly as possible to the front end.

CodePudding user response:

If I understand correctly, you just need to change

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

to this

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

because right now you're passing a function declaration to second argument to axios post function, not a return value from getSpecials

  • Related