【问题标题】:express fetch promise will not resolve before renderexpress fetch 承诺在渲染之前不会解决
【发布时间】:2020-04-18 09:41:07
【问题描述】:

我有一条快速路线,我想将获取的结果发送回我的哈巴狗模板。我知道我的 fetch URL 可以正常工作,因为我已经用邮递员检查过它,并且数据会按原样返回。我想将结果的获取存储到路径底部名为weather 的变量中。在向模板添加天气之前,我的模板会查找此变量是否存在

我还记录了我的表单数据,以确保表单正在将数据发送到我的快递服务器

记录返回时,我在命令控制台中收到此错误:

Promise { <pending> }
(node:18060) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'json' of undefined

我认为问题一定与我的承诺结构有关,或者可能与我的应用中未启用 CORS 有关?我没有收到任何错误,我希望有人可以为我解答??


router.post("/", async(req, res, next)=>{
  console.log(req.body.selectedCity)
  console.log(req.body.selectedState)
  console.log(req.body.selectedZip)

    var result = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${req.body.selectedCity}&units=imperial&appid=${apiKey}`)
      .then(function(result) {
      console.log(result.json())
    })
      .then((result)=>{
        console.log(result.json())
    res.render('index', {states:[
      {
        id:"none",
        name:"choose"
      },
      {
        id:"OH",
        name:"Ohio"
      },
      {
        id:"UT",
        name:"Utah"
      },
      {
        id:"VT",
        name:"Vermont"
      },

      {
        id:"VA",
        name:"Virginia"
      },
      {
        id:"WA",
        name:"Washington"
      },
      {
        id:"WV",
        name:"West Virginia"
      },
      {
        id:"WI",
        name:"Wisconsin"
      },
      {
        id:"WY",
        name:"Wyoming"
      }

    ],weather:result})
  })
});

【问题讨论】:

    标签: express async-await fetch pug


    【解决方案1】:

    这应该改为这种结构 -

    fetch('url')
         .then(result=>result.json)
         .then(result=>res.render())
    

    您还应该从提供给router.post 的回调函数中删除async 关键字。

    【讨论】:

    • 在尝试此操作时,我收到以下错误javaScript json() { var _this2 = this; return consumeBody.call(this).then(function (buffer) { try { return JSON.parse(buffer.toString()); } catch (err) { return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); } }); } 我不确定为什么语法无效?
    【解决方案2】:

    您在 async/await 上的语法不正确。

    您不会在 async/await 中使用 .then,而只需 await 承诺并将结果存储在变量中。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    var result = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${req.body.selectedCity}&units=imperial&appid=${apiKey}`)
          .then(function(result) {
          console.log(result.json())
        })
          .then((result)=>{
            console.log(result.json())
        res.render [...]
    

    变成:

    const result = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${req.body.selectedCity}&units=imperial&appid=${apiKey}`);
    console.log(result.json())
    res.render [...]
    

    尽量避免var,因为它可能会导致意外行为。

    尝试使用axios 作为 fetch 库,它比 fetch 干净得多。

    https://www.npmjs.com/package/axios

    这样就可以const result = await axios.get([...]

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2019-04-13
      • 2021-08-11
      • 1970-01-01
      相关资源
      最近更新 更多