我在/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/