简体   繁体   English

使用 nodeJs 构建网关

[英]Building a gateway with nodeJs

I have to build a layer for an API using nodeJs and create some endpoints for the frontend.我必须使用 nodeJs 为 API 构建一个层,并为前端创建一些端点。 I'm new to nodeJS and I've builded some small servers creating models and making some CRUD with Mongo.我是 nodeJS 的新手,我已经构建了一些小型服务器来创建模型并使用 Mongo 制作一些 CRUD。 This is the first time I have to make an intermediate layer to an existing API to filter the results.这是我第一次必须对现有的 API 做一个中间层来过滤结果。 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:原来的 API 是这样的:

{
  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".我必须从“结果”和“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:这是 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我尝试了不同的东西,但我无法修复它

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.有关参数类型/结构,请参阅所选库的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM