Article directory
nuxt2
Base
- Download, create a new project, or an existing project, we can add the package through yarn (or npm)
yarn add @nuxtjs/axios
- nuxt.config.js configuration
module.exports = { module:['@nuxtjs/axios'], // 可以让我们全局使用 $axios axios:{ // 可以在这里做一些配置代理什么的 }, plugins: ['~/plugins/axios'], //这个会对应咱们下面为axios写的插件 }
add interceptor
Here we need to use plugins, that is, plugins
/plugins/axios.js . We need to create this file as our plugin to process axios
export default function ({
$axios, redirect }) {
$axios.onRequest(config => {
console.log('Making request to ' + config.url)
})
$axios.onError(error => {
const code = parseInt(error.response && error.response.status)
if (code === 400) {
redirect('/400')
}
})
}
Here axios plugin provides some plugins
-
onRequest(config)
-
onResponse(response)
-
onError(err)
-
onRequestError(err)
-
onResponseError(err)
-
setBaseURL
is used to set the URL addressif (process.client) { this.$axios.setBaseURL('http://api.example.com') }
-
setHeader
is used to set the request header Headerthis.$axios.setHeader('Authorization', '456')
-
setToken
can easily set the global authentication header with thisthis.$axios.setToken('123', 'Bearer')
use
Just use it directly, other things nuxtjs has already done for you
async asyncData({
$axios }) {
const ip = await $axios.$get('http://icanhazip.com')
return {
ip }
}