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

问题描述 投票:0回答:4

是否可以使用全局 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;
  });
}

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

vue.js fetch nuxt.js nuxt3
4个回答
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)
    }
  })
})

此插件检查我的

auth
pinia 存储中的令牌,如果存在,则设置标头。

类似的方法可能可用于其他

ofetch
拦截器: ofetch 文档


1
投票

好的,所以 Nuxt3 $fetch 文档说:

Nuxt 使用 ofetch 全局公开 $fetch 助手...

当我们跳转到 ofetch 文档 时,我们可以看到拦截器部分。这为我们提供了一些选择来实现您想要实现的目标。我的建议是这样的:

创建一个

http
可组合(或您想要的任何其他名称):

// composables/use-http.js
const opts = {
  async onRequest({ request, options }) {
    // Add your specific data here
    options.query = { t: '1234' }
    options.headers = { 'Authorization': 'my_token' }
  }
}

export default () => $fetch.create(opts)

这里我们使用 ofetch 的

onRequest
拦截器

onRequest 在 ofetch 被调用时立即被调用,允许修改选项或仅进行简单的日志记录。

您可以在其中添加所需的任何数据,如果需要,您可以创建逻辑以将参数传递给此可组合项等等...

现在,实际获取数据(使用可组合项):

const http = useHttp() // useHttp is auto-imported
const data = await http('/url') // will trigger the interceptor

1
投票

如果您使用存储令牌的 localStorage

    import { ofetch } from "ofetch";

    export default defineNuxtPlugin((_nuxtApp) => {
        globalThis.$fetch = ofetch.create({
            onRequest({ request, options }) {
            if (typeof localStorage !== "undefined") {
                options.headers = { Authorization: `Bearer ${localStorage.getItem("token")}` };
            }
            },
        });
    });


0
投票

这是 Nuxt 团队建议的一种有趣的方法,它允许您使用默认值和用户身份验证令牌自定义获取请求:

https://nuxt.com/docs/examples/advanced/use-custom-fetch-composable

这是一个自定义可组合项(摘自上面的示例):

import type { UseFetchOptions } from 'nuxt/app';

export function useCustomFetch<T>(
  url: string | (() => string),
  options: UseFetchOptions<T> = {}
) {
  return useFetch(url, {
    ...options,
    $fetch: useNuxtApp().$customFetch,
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.