expressfetchexpress-handlebars

How can I render fetch on an express page


I've been trying for two days now to understand how to work with fetch in my case. Perhaps I just don’t understand the principle of how to work with it correctly in express. I've already read a lot, I have the fetch result I need, but I can't find anywhere how to show it in express. This is my code:

import { fortunes, fetchAdvice } from './predictions.js'

app.engine('.hbs', engine({ extname: '.hbs' }))
app.set('view engine', '.hbs')
app.set('views', './views')

app.use(express.static(path.resolve(process.cwd(), 'static')))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.get('/about', async (req, res) => {
  // Prediction Index Calculation & This is the page for publishing fetch
  const randomFortune = fortunes[Math.floor(Math.random() * fortunes.length)]
  res.render('about', {
    fortune: randomFortune,
    advice: await fetchAdvice().then((advice) => {
      advice.text.toUpperCase()
    }),
  })
})

Here is a request to the public API, it works correctly and console.log displays the result I need. predictions.js:

const fortunes = ['Conquer your fears or they will conquer you.', 'Rivers need sources.']

const fetchAdvice = async () => {
  const res = await fetch(url_random)
  if (res.ok) {
    const advice = await res.json()
    console.log(`${advice.text.toUpperCase()}`) // Here the type is String
    return advice
  }
}

fetchAdvice().then((advice) => {
  advice.text.toUpperCase()
})

export { fortunes, fetchAdvice }

This is the handlebars page where I publish two dynamic variables, the first one is from the fortunes array and there are no problems here (statics are statics), and I’m trying to implement the second one using fetch. I tried making res.render both asynchronous and without async / await , in the first case I get [object Promise] , which is expected, in the second (as in the code), in the js console of the browser the rendering does not happen at all.

about.hbs:

{{#if fortune}}
  <p>Your prediction for today: {{fortune}}</p>
{{/if}}

{{#if advice}}
  <p>Your advice for today: {{advice}}</p>
{{/if}}

Solution

  • app.get('/about', async (req, res) => {
      // Prediction Index Calculation & This is the page for publishing fetch
      const randomFortune = fortunes[Math.floor(Math.random() * fortunes.length)]
      res.render('about', {
        fortune: randomFortune,
        advice: await fetchAdvice().then((advice) => {
          return advice.text.toUpperCase() // We need to add return, that was the problem!
        }),
      })
    })