简体   繁体   中英

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:

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!

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 -

res.json({yourKey : yourValue});

Where res is the response object you receive with request. For more details refer this expressjs doc.

You can use the response object to send to the browser.

There are several ways to that,

  • res.send(jsonObject);
  • res.json(jsonObject);
  • res.status(statusCode).json(jsonObject); Take a look at the api reference .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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