-1

Using Google's api I'm able to get places nearby printed to the console

router.get('/', function (req, res, next) {
 // Find places nearby
      googleMapsClient.placesNearby({
          language: 'en',
          location: [-33.865, 151.038],
          radius: 500,
          type: 'restaurant'
        })
        .asPromise()
        .then((response) => {
          console.log(response.json.results);
        })
        .catch((err) => {
          console.log(err);
        });
    });

I want to send the response which has all the places nearby to the client so I can print them in a table using pug.

I'm having trouble sending that data, when I try res.send(response.json.results

I get Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

  • There's no such thing as `response.send()` in your code, only `res.send()`. Please take 30 seconds to re-read your code and edit your question if you still have a problem. – Azami Feb 18 '19 at 22:56
  • Wrong. the response comes from Google's. and res from express route. – Phillips Mark Feb 18 '19 at 22:59
  • Check ` .then((response) => {` – Phillips Mark Feb 18 '19 at 22:59
  • I'm glad you edited, but your previous post was mentioning `TypeError: response.send is not a function`, to which I said response.send() can't be a thing ;) – Azami Feb 18 '19 at 23:00
  • Can you add back res.send(response.json.results) exactly how you are attempting? – cantuket Feb 18 '19 at 23:11
  • The code you have provided will not throw the error you have indicated. You left out something important. at least two somethings. – Kevin B Feb 18 '19 at 23:27

2 Answers2

0

Following the express documentation, https://expressjs.com/en/api.html#res ,you could do:

.then(response => {
   res.send(response).
})

or

.then(response => {
  res.json(response)
})

Just check if you have to use .asPromise() before then.

0
router.get('/', async function (req, res, next) {

      let response = await googleMapsClient.placesNearby({
          language: 'en',
          location: [-33.865, 151.038],
          radius: 500,
          type: 'restaurant'
        })
        .asPromise()
        .catch((err) => {
          console.log(err);
        });
      console.log(response.json.results);
      return res.send(response.json.results)

});

Error: Can't set headers after they are sent to the client

cantuket
  • 1,582
  • 10
  • 19