【问题标题】:Building a gateway with nodeJs使用 nodeJs 构建网关
【发布时间】:2021-06-29 00:39:19
【问题描述】:

我必须使用 nodeJs 为 API 构建一个层,并为前端创建一些端点。 我是 nodeJS 的新手,我已经构建了一些小型服务器来创建模型并使用 Mongo 制作一些 CRUD。 这是我第一次必须对现有 API 做一个中间层来过滤结果。 我做到了,并且采用了预期的格式,但是我从节点收到了一个错误,我不知道如何解决它。

原来的 API 是这样的:

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

我必须从“results”和“additional_info”的第一个数组中“提取”数据。

我的端点必须以这种格式返回数据:

{
  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'},
    …]
}

我可以做到这一点:

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

这是控制器:

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


端点看起来像这样:

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

这是错误

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

我尝试了不同的方法,但我无法修复它

【问题讨论】:

  • res.json(response); 而不是 res.send(response).json();

标签: javascript node.js express async-await api-gateway


【解决方案1】:

首先,您的错误在这里有一个解释: Error: Can't set headers after they are sent to the client

对于您的代码:

看这个:


res.send(response).json();

它应该是以下之一:


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

有关参数类型/结构,请参阅所选库的文档。

【讨论】:

  • 谢谢!我到处找,但我看不到 res.send(response).json(); 的错误;
猜你喜欢
  • 1970-01-01
  • 2014-12-19
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 2018-12-03
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多