使用全局 onRequest 处理程序在 nuxt3 中重新定义 $fetch

Twi*_*ist 3 fetch vue.js nuxt.js nuxt3

是否可以使用全局 onRequest 处理程序通过 Nuxt3 进行 $fetch,以在每个请求上添加特定数据?使用 nuxt2 和 axios 就很简单

/plugins/axios.js

export default function ({ $axios, store, req }) {
  $axios.onRequest((config) => {
    if (config.data) {
      config.data.test = '123';
    } else {
      config.data = { test: '123' };
    }
    return config;
  });
}
Run Code Online (Sandbox Code Playgroud)

但是如何在 Nuxt3 和 $fetch 上实现相同的目标呢?

小智 11

Nuxt v3.3.2 似乎正在使用globalThis.$fetch它的 useFetch 请求,它是ofetch.

我做了一个插件ofetch.ts,内容如下:

import { ofetch } from 'ofetch'
import { useAuthStore } from '~/store/auth'

export default defineNuxtPlugin((_nuxtApp) => {
  globalThis.$fetch = ofetch.create({
    onRequest ({ _request, options }) {
      const authStore = useAuthStore()
      if (authStore.isAuthenticated) {
        options.headers = { Authorization: `Bearer ${authStore.token}` }
        console.log(options)
      } else {
        console.log('Not authenticated')
      }
    },
    onRequestError ({ error }) {
      console.error(error)
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

该插件检查我的authpinia 存储中是否有令牌,如果存在,则设置标头。

类似的方法可能可用于其他ofetch拦截器: ofetch docs