3

我正在尝试过滤一个对象,这些对象是从array我的. 我正在使用Web 框架进行调用。JSONAPIproxyNode.jsExpressAPI

API 返回以下内容:

{
  data: [
    {
      type: "aaa",
      name: "Cycle",
      id: "c949up9c",
      category: ["A","B"]
    },
    {
      type: "bbb",
      name: "mobile",
      id: "c2rt4Jtu",
      category: ["C","D"]
    },
   ...
   ]
}

服务器.js

function sortDataByID(data) {
  return data.filter(function(item) {
     return item.id == 'c949up9c';
});
}

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options).pipe(sortDataByID(res));
});

我不断收到以下错误消息。

类型错误:data.filter 不是函数

这里明显的错误是什么?任何人?

4

3 回答 3

3

我认为您的错误是认为比您预期res的要多。data

但是如果你看一下内部res,你应该会发现data.

所以你必须从中获取datares使用它。

例如:

const data = res.data;
request.get(options).pipe(sortDataByID(data))

祝你今天过得愉快 !

于 2017-11-15T12:18:10.647 回答
1

I received TypeError: data.filter is not a function while doing Unit testing.

I was passing an object not an array in the result. gateIn$: of({}), instead of gateIn$: of([]),

gateIn$.pipe(takeUntil(this.destroy$)).subscribe(bookings => (this.dataSource.data = bookings));

once you see the error it is pretty obvious, the hard bit is spotting it in the first place.

于 2021-02-03T22:13:45.330 回答
1

我个人从未见过管道到函数。我认为这不应该奏效。任何状况之下:

您可以使用回调而不是管道。尝试这个:

app.get('/products', (req, res) => {
 const options = {
 url: BASE_URL + '/products',
 json: true, //little convenience flag to set the requisite JSON headers
 headers: {
  'Authorization': 'hgjhgjh',
  'Accept': 'application/json'
 }
}
  request.get(options, sortDataByID);

});

function sortDataByID(err, response, data){ //the callback must take 3 parameters

    if(err){
        return res.json(err); //make sure there was no error
    }

    if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
        return res.status(400).json(err)
    }

    let dataToReturn =  data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
        return item.id == 'c949up9c';
    }

    res.json(dataToReturn);
}
于 2017-11-15T13:04:05.440 回答