地址:https://www.homwang.com 歡迎大家性能測(cè)試
交流討論——QQ群號(hào):604203227
?? Axios
安全巨坊,輕松的Axios與Nuxt.js集成
特性
? 自動(dòng)為客戶端和服務(wù)器端設(shè)置基本URL
? 公開(kāi)功能灾票,以便我們可以輕松地全局設(shè)置身份驗(yàn)證令牌setToken$axios
? 請(qǐng)求基本URL時(shí)自動(dòng)啟用withCredentials
? SSR中的代理請(qǐng)求頭(對(duì)于auth有用)
? 獲取樣式請(qǐng)求
? 在提出請(qǐng)求時(shí)與Nuxt.js Progressbar集成
? 集成 Proxy Module
? 具有自動(dòng)重試請(qǐng)求 axios-retry
使用
yarn 和 npm 安裝:
yarn add @nuxtjs/axios
OR
npm install @nuxtjs/axios
nuxt.config.js
module.exports = {
modules: [
'@nuxtjs/axios',
],
?
axios: {
// proxyHeaders: false
}
}
Component
asyncData
async asyncData({ $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
return { ip }
}
methods
/created
/mounted
/etc
methods: {
async fetchSomething() {
const ip = await this.$axios.$get('http://icanhazip.com')
this.ip = ip
}
}
Store nuxtServerInit
async nuxtServerInit ({ commit }, { $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
Store actions
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}
擴(kuò)展
如果您需要通過(guò)注冊(cè)攔截器和更改全局配置來(lái)自定義axios,則必須創(chuàng)建一個(gè)nuxt插件汞窗。
nuxt.config.js
{
modules: [
'@nuxtjs/axios',
],
?
plugins: [
'~/plugins/axios'
]
}
plugins/axios.js
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')
}
})
}
攔截器
Axios插件提供幫助程序礁竞,可以更輕松,更快速地注冊(cè)axios攔截器杉辙。
onRequest(config)
onResponse(response)
onError(err)
onRequestError(err)
onResponseError(err)
默認(rèn)情況下模捂,這些函數(shù)不必返回任何內(nèi)容。
示例: (plugins/axios.js)
export default function ({ $axios, redirect }) {
$axios.onError(error => {
if(error.code === 500) {
redirect('/sorry')
}
})
}
獲取樣式請(qǐng)求
Axios插件還支持使用前綴 $
的樣式方法來(lái)獲取請(qǐng)求:
// Normal usage with axios
let data = (await $axios.get('...')).data
?
// Fetch Style
let data = await $axios.$get('...')
設(shè)置頭部信息
setHeader(name, value, scopes='common')
Axios實(shí)例有一個(gè)幫助方法蜘矢,可以輕松設(shè)置任何標(biāo)頭狂男。
參數(shù):
- name: 標(biāo)題的名稱
- value: 標(biāo)頭的值
-
scopes: 默認(rèn)僅針對(duì)特定類型的請(qǐng)求發(fā)送。
- Type: 數(shù)組或字符串
- Defaults: 默認(rèn)所有類型的請(qǐng)求為
common
- 可以是
get
,post
,delete
, ...
// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')
?
// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')
?
// Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
'post'
])
?
// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])
設(shè)置Token
setToken(token, type, scopes='common')
Axios實(shí)例有一個(gè)幫助方法品腹,可以輕松設(shè)置全局身份驗(yàn)證標(biāo)頭岖食。
參數(shù):
- token: 授權(quán)令牌
-
type: 授權(quán)令牌前綴(通常為
Bearer
) -
scopes: 默認(rèn)僅針對(duì)特定類型的請(qǐng)求發(fā)送。
- Type: 數(shù)組或字符串
- Defaults: 默認(rèn)所有類型的請(qǐng)求為
common
- 可以是
get
,post
,delete
, ...
// Adds header: `Authorization: 123` to all requests
this.$axios.setToken('123')
?
// Overrides `Authorization` header with new value
this.$axios.setToken('456')
?
// Adds header: `Authorization: Bearer 123` to all requests
this.$axios.setToken('123', 'Bearer')
?
// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])
?
// Removes default Authorization header from `common` scope (all requests)
this.$axios.setToken(false)
選項(xiàng)
您可以使用 axios
模塊選項(xiàng)或部分選項(xiàng)在 nuxt.config.js
配置
prefix
舞吭、host
和port
該選項(xiàng)使用在 baseURL
和 browserBaseURL
可以自定義 API_PREFIX, API_HOST (或 HOST) 和 API_PORT (或 PORT) 環(huán)境變量泡垃。
prefix
的默認(rèn)值為 /
baseURL
- Default:
baseURL
(或prefix
在使用options.proxy
啟用)
在客戶端使用和預(yù)先添加請(qǐng)求的基本URL析珊。
環(huán)境變量 API_URL_BROWSER
可用于覆蓋 browserBaseURL
https
- Default:
false
如果設(shè)置為 true
,http://
在 baseURL
和 browserBaseURL
將會(huì)變成 https://
progress
- Default:
true
在和Nuxt.js集成時(shí)并發(fā)出請(qǐng)求時(shí)顯示加載條(只有在瀏覽器上加載條時(shí)可用)
還可以使用 progress
配置禁用每個(gè)請(qǐng)求的進(jìn)度條蔑穴。
nuxt.config.js
{
modules: [
'@nuxtjs/axios'
],
?
axios: {
proxy: true // Can be also an object with default options
},
?
proxy: {
'/api/': 'http://api.example.com',
'/api2/': 'http://api.another-website.com'
}
}
注意:不需要手動(dòng)注冊(cè) @nuxtjs/proxy
模塊忠寻,但它確實(shí)需要在您的依賴項(xiàng)中。
注意:將 /api
添加到API端點(diǎn)的所有請(qǐng)求中存和。如果需要?jiǎng)h除它奕剃,請(qǐng)使用 /pathRewrite
:
proxy: {
'/api/': { target: 'http://api.example.com', pathRewrite: {'^/api/': ''} }
}
retry
- Default:
false
- 自動(dòng)攔截失敗的請(qǐng)求,并在每次使用 axios-retry 時(shí)重試它們捐腿。
默認(rèn)情況下纵朋,如果將 retry
值設(shè)置為 true
,則重試次數(shù)將為3次茄袖。您可以通過(guò)傳遞這樣的對(duì)象來(lái)更改它:
axios: {
retry: { retries: 3 }
}
credentials
- Default:
false
添加攔截器時(shí)自動(dòng)設(shè)置 withCredentials
操软,請(qǐng)求axios時(shí)配置 baseUrl
,允許將身份驗(yàn)證頭傳遞給后端
debug
- Default:
false
添加攔截器來(lái)記錄請(qǐng)求和響應(yīng)宪祥。
proxyHeaders
- Default:
true
在SSR上下文中聂薪,將客戶端請(qǐng)求頭設(shè)置為axios的默認(rèn)請(qǐng)求頭。這對(duì)于在服務(wù)器端進(jìn)行需要基于cookie的auth的請(qǐng)求很有用品山。還有助于在SSR和客戶端代碼中做出一致的請(qǐng)求。
注意:如果在受CloudFlare CDN保護(hù)的URL上請(qǐng)求烤低,則應(yīng)將其設(shè)置為false肘交,以防止CloudFlare錯(cuò)誤地檢測(cè)到反向代理循環(huán)并返回403錯(cuò)誤。
proxyHeadersIgnore
- Default:
['host', 'accept']
只有在 proxyHeaders
設(shè)置為true 時(shí)才有效扑馁。將不需要的請(qǐng)求標(biāo)頭移除到SSR中的API后端涯呻。
附加問(wèn)題時(shí)間:2019-10-9
問(wèn)題一:很多才接觸的小伙伴不知道怎樣在js文件中使用$axios
答:普通js文件需要在plugins插件目錄中添加一個(gè).js文件,然后在nuxt.config.js插件配置中添加該插件
示例:
plugins目錄添加的.js
export default (context, inject) => {
// context.$axios 獲取axios
}
nuxt.config.js Nuxt配置文件
plugins: [
'~plugins/**',
'~plugins/**'
]