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

标签 node.js express

我在/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);
    });
});

我尝试在浏览器中返回这些 json 对象,而不是 console.logging 每个列表!

我尝试查找,但似乎找不到适合我的问题的措辞。

最佳答案

您可以使用响应对象发送到浏览器。

有几种方法可以实现这一点,

  • res.send(jsonObject);
  • res.json(jsonObject);
  • res.status(statusCode).json(jsonObject); 看看api reference .

所以你的方法可以是

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

这里,抓取数据库结果后,我们将其发送到客户端,而不是显示在控制台中。

关于node.js - 如何将这些 JSON 对象返回到浏览器而不是控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52921839/

相关文章:

javascript - 允许用户管理 npm 模块的依赖版本

node.js - 是否有可能在 Github Codespaces 中更新 node.js?

node.js - Node 断言 : Test error message

javascript - Node Busboy 中止上传

javascript - 如何迭代对象数组以便将数据推送到 Mongodb 嵌套数组中

javascript - 使用 Gulp + Browserify 时,对象 #<Readable> 没有方法 'write'

javascript - Webpack 开发中间件未正确提供 bundle.js

node.js - 如何使用 passport-spotify 将用户重定向回上一页

node.js - 如何处理多个域?

node.js - Node.js 和 Express.js 的 POST 请求失败