簡體   English   中英

使用 nodeJs 構建網關

[英]Building a gateway with nodeJs

我必須使用 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
        },
        {...},
        {...}
      ],
    },
    {...},
    {...}
  ]
}

我必須從“結果”和“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);
  }
};

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


端點看起來像這樣:

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

這是錯誤

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

我嘗試了不同的東西,但我無法修復它

首先,您的錯誤在這里有一個解釋: 錯誤:在將標頭發送到客戶端后無法設置標頭

對於您的代碼:

看看這個:


res.send(response).json();

它應該是其中之一:


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

有關參數類型/結構,請參閱所選庫的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM