0

我有一个托管在 Netlify 上的 Nuxt 静态应用程序。在mounted()钩子中,我调用了一个设置 cookie 的 Netlify 函数。这发生在页面加载并正常工作之后。

问题是,您可以在页面加载之前进行初始调用吗?Netlify 是否提供了某种方式来做到这一点?

Nuxt/Vue 代码:

mounted () {
  this.myFirstFunctionCall()
},
methods: {
  async myFirstFunctionCall () {
    const funcUrl = '/.netlify/functions/my-initial-function'

    await this.$axios
      .$get(funcUrl)
      .then((res) => {
        console.log(res)
      })
      .catch((error) => {
        console.error(error)
      })
  }
}

被调用的 Netlify 函数:

exports.handler = async function (event) {
  const COOKIE_NAME = 'myfirstcookie'
  let cookieValue = null

  try {
    await getDataFromSomewhere
    // ...
    cookieValue = someDataThatJustGotFetched
  } catch (err) {
    console.log(err)
  }

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
      'Set-Cookie': COOKIE_NAME + '=' + cookieValue + '; Path=/; SameSite=Lax;'
    },
    body: JSON.stringify({ hello: 'world' })
  }
}
4

0 回答 0