如何在Nuxt中全局挂载Axios及Axios拦截器?
Great question! Setting up a global Axios instance with interceptors in Nuxt (so it's accessible everywhere like i18n) is totally doable—let's walk through it step by step, covering both Nuxt 2 and Nuxt 3 since their setups differ a bit.
Nuxt 2 Setup
Nuxt 2 has an official Axios module that simplifies global configuration, so we'll use that.
Step 1: Install the Official Axios Module
First, add the module to your project:
npm install @nuxtjs/axios # OR yarn add @nuxtjs/axios
Step 2: Configure the Module in nuxt.config.js
Enable the module and set any global Axios defaults (like your API base URL) in your config file:
// nuxt.config.js export default { modules: [ '@nuxtjs/axios', ], // Optional: Set base URL and other defaults axios: { baseURL: 'https://your-api-base-url.com' } }
Step 3: Create an Axios Plugin for Interceptors
Create a plugins/axios.js file to define your global interceptors. This plugin gets access to Nuxt's context, including the pre-configured $axios instance:
// plugins/axios.js export default function ({ $axios, redirect }) { // Request interceptor: Runs before every request is sent $axios.onRequest(config => { console.log('Sending request to:', config.url) // Example: Attach auth token to headers const token = localStorage.getItem('auth-token') if (token) { config.headers.common['Authorization'] = `Bearer ${token}` } return config }) // Response interceptor: Runs after a successful response $axios.onResponse(response => { console.log('Response received:', response.status) // Example: Return only the data payload instead of the full response return response.data }) // Error interceptor: Handles request failures $axios.onError(error => { const statusCode = error.response?.status if (statusCode === 401) { // Redirect to login if unauthorized redirect('/login') } return Promise.reject(error) }) }
Step 4: Register the Plugin
Add the plugin to your nuxt.config.js so Nuxt loads it on startup:
// nuxt.config.js export default { // ... other config plugins: [ '~/plugins/axios.js' ] }
Using the Global Axios Instance
Now $axios is available everywhere in your project:
- In Vue components:
this.$axios.get('/api/data') - In
asyncData/fetch:async asyncData({ $axios }) { const data = await $axios.get('/api/data'); return { data } } - In Vuex actions:
this.$axios.post('/api/login', credentials)
Nuxt 3 Setup
Nuxt 3 uses a plugin-based system with auto-imports, so we'll create a custom Axios instance and inject it globally.
Step 1: Install Axios
Install the standard Axios package (Nuxt 3 doesn't have an official module like Nuxt 2):
npm install axios # OR yarn add axios
Step 2: Create an Axios Plugin
Create plugins/axios.ts (or .js if you're not using TypeScript) to define your instance and interceptors:
// plugins/axios.ts import axios from 'axios' export default defineNuxtPlugin(nuxtApp => { // Create a custom Axios instance const api = axios.create({ baseURL: 'https://your-api-base-url.com', headers: { common: { 'Accept': 'application/json, text/plain, */*' } } }) // Request interceptor api.interceptors.request.use(config => { console.log('Request sent to:', config.url) // Add auth token (use Nuxt 3's useCookie for SSR compatibility) const token = useCookie('auth-token').value if (token) { config.headers.Authorization = `Bearer ${token}` } return config }, error => Promise.reject(error)) // Response interceptor api.interceptors.response.use(response => { console.log('Response received:', response.status) return response.data }, error => { if (error.response?.status === 401) { nuxtApp.$router.push('/login') } return Promise.reject(error) }) // Inject the instance into the Nuxt app nuxtApp.provide('axios', api) })
Step 3: Use the Global Axios Instance
Nuxt 3 auto-detects plugins in the plugins directory, so no extra config is needed. To use it:
- In Vue components/composables:
<script setup> const { $axios } = useNuxtApp() const fetchData = async () => { const data = await $axios.get('/api/data') console.log(data) } </script>
- In server routes:
// server/api/hello.ts import { useNuxtApp } from '#app' export default defineEventHandler(async (event) => { const { $axios } = useNuxtApp() const data = await $axios.get('/external-api/data') return data })
That's it! With these setups, every request made through the global $axios instance will pass through your interceptors—just like how i18n is accessible across your Nuxt project.
内容的提问来源于stack exchange,提问作者user7788669

