简体   繁体   English

如何将这些JSON对象返回到浏览器而不是控制台

[英]How do I return these JSON objects to my browser instead of the console

Im receiving and displaying some JSON objects in /hello as seen below: 我在/ hello中接收并显示一些JSON对象,如下所示:

app.get('/hello' , (req, res) => {
  client
    .search('leather couch')
    .then((listings) => {
      // filtered listings (by price)
      console.log("got here");
      listings.forEach((listing) =>  console.log(listing));

    })
    .catch((err) => {
      console.error(err);
    });
});

instead of console.logging each listing im trying to return these json objects in the browser! 而不是console.logging每个列表,我试图在浏览器中返回这些json对象!

I tried looking it up but can't seem to find the right wording to my question. 我尝试查找它,但似乎找不到适合我问题的措辞。

You can send a success JSON response like this - 您可以像这样发送成功的JSON响应-

res.json({yourKey : yourValue});

Where res is the response object you receive with request. 其中res是随请求一起收到的响应对象。 For more details refer this expressjs doc. 有关更多详细信息,请参阅此expressjs文档。

You can use the response object to send to the browser. 您可以使用响应对象发送到浏览器。

There are several ways to that, 有几种方法可以做到这一点,

  • res.send(jsonObject); res.send(的JSONObject);
  • res.json(jsonObject); res.json(的JSONObject);
  • res.status(statusCode).json(jsonObject); res.status(的StatusCode)上传.json(的JSONObject); Take a look at the api reference . 看一下api参考

So your approach can be 所以你的方法可以是

app.get('/hello' , (req, res) => {
  client
    .search('leather couch')
    .then((listings) => {
      // filtered listings (by price)
      return res.status(200).json(listing);
    })
    .catch((err) => {
      console.error(err);
    });
});

Here, after grabbing the database result, we send it to the client instead of displaying in the console. 在这里,获取数据库结果后,我们将其发送给客户端,而不是显示在控制台中。

You can use res.send() to return 您可以使用res.send()返回

app.get('/hello' , (req, res) => {
   client
   .search('leather couch')
   .then((listings) => {
       res.send({ list: listings });
   })
   .catch((err) => {
       console.error(err);
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM