如何从快递服务器返回json?

时间:2017-11-05 06:23:51

标签: javascript json reactjs axios

我已经使用express.js构建了一个服务器,其中一部分看起来像这样:

app.get("/api/stuff", (req, res) => {
  axios.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1').then(function(response){
    res.send(response);
    console.log('response=',response);
  })
});

当我点击api / stuff'它返回一个错误:

  

(node:1626)UnhandledPromiseRejectionWarning:未处理的承诺   rejection(rejection id:1):TypeError:转换循环结构   到JSON

如何从终端返回json?

1 个答案:

答案 0 :(得分:2)

从开放天气API获得的response对象是圆形类型(引用自身的对象)。 JSON.stringify在通过循环引用时会抛出错误。这是使用send方法时出现此错误的原因。

要避免这种情况,只需将所需数据作为响应发送

app.get("/api/stuff", (req, res) => {
  axios.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1').then(function(response){
    res.send(response.data);
    console.log('response=',response.data);
  })
});