0

I have to build a layer for an API using nodeJs and create some endpoints for the frontend. I'm new to nodeJS and I've builded some small servers creating models and making some CRUD with Mongo. This is the first time I have to make an intermediate layer to an existing API to filter the results. I did it, and in the expected format, but I'm getting an error from node and I can't figure out how to resolve it.

The original API is kind like this:

{
  id:'some id',
  pagination: {...},
  results: [...],
  other_results: [...],
  additional_info: [
    {
      id:'someid',
      info:'someinfo',
      values:[
        {
          id: 'someid',
          name: 'some category name',
          count: 999
        },
        {...},
        {...}
      ],
    },
    {...},
    {...}
  ]
}

and I have to "extract" the data from "results" and the first array of "additional_info".

My endpoint has to return data in this format:

{
  brand: {name: "Any brand", country: "Germany"},
  categories: ["category one", "category two", "category three"],
  items: [
    0: {id: "olmk23238777", name: "item one", imgUrl: 'img/34341.jpg', price: {total:424, currency: "USD"}, shipping: 'fast'},
    1: {id: "olmk23239348", name: "item two", imgUrl: 'img/34764.jpg', price: {total:47, currency: "USD"}, shipping: 'slow'},
    …]
}

I could achieved with this:

const axios = require('axios');

exports.products = async query => {
  const url = `${process.env.BASE_URL}${query}`;

  let productsData = {
    brand: {
      name: 'Any Brand',
      country: 'Germany',
    },
  };

  try {
    const result = await axios({
      method: 'GET',
      url,
    });
    const data = result.data;
    productsData.categories = data.additional_info[0].values.map(
      ({ categoryName }) => categoryName
    );
    productsData.items = data.results.map(item => ({
      id: item.id,
      name: item.name,
      imgUrl: item.imgSrc,
      price: {
        total: parseInt(item.price),
        currency: item.currency,
      },
      shipping: item.shipping_method,
    }));

    return productsData;
  } catch (error) {
    console.log(error);
  }
};

This is the controller:

const { products } = require('../utils/products');

exports.searchItem = async (req, res) => {
  const { search } = req.query;
  try {
    const response = await products(search);
    res.send(response).json();
  } catch (error) {
    console.log(error);
  }
};


and the endpoint look like this:

http://localhost:4000/api/products?search=shirt

This is the error

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I tried different things but I can't fixe it

Maaart
  • 55
  • 5

1 Answers1

0

First of all, your error has an explanation here: Error: Can't set headers after they are sent to the client

And for your code:

look this:


res.send(response).json();

it should be one of these:


res.send(response);
// or
res.json(response);

For the parameter type/structure, please refer to documentation of your selected library.

Khoa
  • 2,632
  • 18
  • 13
  • 1
    Thanks! I was looking everywhere but I couldn't see my mistake with the res.send(response).json(); – Maaart Apr 02 '21 at 04:55