In Nuxt 3 how to set the global API baseUrl used in useFetch
P粉757432491
P粉757432491 2023-10-22 18:54:21
0
1
943

How to set the baseUrl used in the global useFetch composable (probably nuxt.config.ts)?

How to avoid defining it in every useFetch?

P粉757432491
P粉757432491

reply all (1)
P粉638343995

You can definebaseURLinnuxt.config.js|tslike this:

import { defineNuxtConfig } from 'nuxt' export default defineNuxtConfig({ // ... runtimeConfig: { public: { baseURL: process.env.BASE_URL || 'https://api.example.com/', }, }, // ...

(or use fixed values or just environment variables - depending on your preference)

and add this composable:

// /composables/useMyFetch.js export const useMyFetch = (request, opts) => { const config = useRuntimeConfig() return useFetch(request, { baseURL: config.public.baseURL, ...opts }) }

If you want type safety, you can achieve it like this:

// /composables/useMyFetch.ts export const useMyFetch: typeof useFetch = (request, opts?) => { const config = useRuntimeConfig() return useFetch(request, { baseURL: config.public.baseURL, ...opts }) }

You can then useuseMyFetchas a replacement foruseFetch- but set the baseURL :-)

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!