Express中间件:错误:TypeError:将圆形结构转换为JSON

时间:2019-04-03 19:37:19

标签: javascript node.js express

我将以下函数用作中间件,只是为了增加要添加到我的数组中的新对象的ID:

def percentileofscore(a, score, kind='rank'):    
    n = len(a)
    if n == 0:
        return 100.0
    left = len([item for item in a if item < score])
    right = len([item for item in a if item <= score])
    if kind == 'rank':
        pct = (right + left + (1 if right > left else 0)) * 50.0/n
        return pct
    elif kind == 'strict':
        return left / n * 100
    elif kind == 'weak':
        return right / n * 100
    elif kind == 'mean':
        pct = (left + right) / n * 50
        return pct
    else:
        raise ValueError("kind can only be 'rank', 'strict', 'weak' or 'mean'")

当我发布新狮子时,它将遵循以下路线:

let lions = []
let id = 0

const updateId = function(req, res, next) {
  if (!req.body.id) {
    id++;
    req.body.id = id + '';
  }
  next();
};

开机自检有效且创建了新狮子,但是出现以下错误。关于如何解决它的任何想法?

  

[nodemon]从app.post('/lions', updateId, (req, res) => { console.log('POST req', req.body) const lion = req.body; lions.push(lion) res.json(req) }) 开始   节点在端口上运行:3000   取得狮子:[]   错误:TypeError:将圆形结构转换为JSON       在JSON.stringify()       在stringify(/Users/leongaban/projects/tutorials/pluralsight/api-design-node/node_modules/express/lib/response.js:1119:12)

server.js

node server.js

1 个答案:

答案 0 :(得分:0)

  

可能是因为,在这一行上:app.post()方法的res.json(req),req对象包含一个内部属性,该属性引用一个外部属性,从而创建了一个循环引用。使用console.log()检查该对象的结构,或者如果在响应中返回其他内容,则可以避免该问题。

     

– Shidersz

需要先创建一个新变量,然后再将其传递到put函数的res.json中

app.param('id', (req, res, next, id) => {
  let lion = lions.filter((lion => lion.id === id))

  if (lion) {
    req.lion = lion;
    next();
  } else {
    res.send();
  }
})

app.get('/lions', (req, res, next) => {
  console.log('GET lions:', lions)
  res.json(lions)
})

app.get('/lions/:id', (req, res) => {
  console.log('GET lion:', req.lion)
  const lion = req.lion // <-- here
  res.json(lion || {})  // <-- then here instead of passing req
})