【问题标题】:Returning the value inside .then() [duplicate]返回 .then() 中的值 [重复]
【发布时间】:2019-07-12 09:13:18
【问题描述】:

使用 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

【问题讨论】:

  • 您的代码中没有response.send() 这样的东西,只有res.send()。如果仍有问题,请花 30 秒时间重新阅读您的代码并编辑您的问题。
  • 错了。响应来自谷歌的。和快速路线的资源。
  • 检查`.then((response) => {`
  • 我很高兴你编辑了,但你之前的帖子提到了TypeError: response.send is not a function,我说 response.send() 不可能是一件事;)
  • 你能准确地添加 res.send(response.json.results) 吗?

标签: javascript node.js google-maps express


【解决方案1】:

按照快递文档https://expressjs.com/en/api.html#res,您可以这样做:

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

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

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

【讨论】:

    【解决方案2】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      相关资源
      最近更新 更多