返回.then()内部的值

时间:2019-02-18 22:52:53

标签: javascript node.js google-maps express

使用Google的api,我可以将附近的位置打印到控制台上

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

我想将附近所有地点的响应发送给客户端,以便我可以使用pug将其打印在表中。

尝试res.send(response.json.results

时,我无法发送该数据

我得到Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

2 个答案:

答案 0 :(得分:0)

按照快速文档https://expressjs.com/en/api.html#res,您可以执行以下操作:

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

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

请在此之前检查是否必须使用.asPromise()。

答案 1 :(得分: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