安全,輕松的Axios與Nuxt.js集成

地址:https://www.homwang.com 歡迎大家性能測試
交流討論——QQ群號:604203227

?? Axios

安全,輕松的Axios與Nuxt.js集成

特性

? 自動為客戶端和服務(wù)器端設(shè)置基本URL

? 公開功能,以便我們可以輕松地全局設(shè)置身份驗(yàn)證令牌setToken$axios

? 請求基本URL時(shí)自動啟用withCredentials

? SSR中的代理請求頭(對于auth有用)

? 獲取樣式請求

? 在提出請求時(shí)與Nuxt.js Progressbar集成

? 集成 Proxy Module

? 具有自動重試請求 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ò)展

如果您需要通過注冊攔截器和更改全局配置來自定義axios,則必須創(chuàng)建一個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插件提供幫助程序,可以更輕松,更快速地注冊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')
    }
  })
}

獲取樣式請求

Axios插件還支持使用前綴 $ 的樣式方法來獲取請求:

// 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í)例有一個幫助方法,可以輕松設(shè)置任何標(biāo)頭。

參數(shù):

  • name: 標(biāo)題的名稱
  • value: 標(biāo)頭的值
  • scopes: 默認(rèn)僅針對特定類型的請求發(fā)送。
    • Type: 數(shù)組或字符串
    • Defaults: 默認(rèn)所有類型的請求為 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í)例有一個幫助方法,可以輕松設(shè)置全局身份驗(yàn)證標(biāo)頭。

參數(shù):

  • token: 授權(quán)令牌
  • type: 授權(quán)令牌前綴(通常為 Bearer
  • scopes: 默認(rèn)僅針對特定類型的請求發(fā)送。
    • Type: 數(shù)組或字符串
    • Defaults: 默認(rèn)所有類型的請求為 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、hostport

該選項(xiàng)使用在 baseURLbrowserBaseURL

可以自定義 API_PREFIX, API_HOST (或 HOST) 和 API_PORT (或 PORT) 環(huán)境變量。

prefix 的默認(rèn)值為 /

baseURL

  • Default: baseURL (或 prefix 在使用 options.proxy 啟用)

在客戶端使用和預(yù)先添加請求的基本URL。

環(huán)境變量 API_URL_BROWSER 可用于覆蓋 browserBaseURL

https

  • Default: false

如果設(shè)置為 true,http://baseURLbrowserBaseURL 將會變成 https://

progress

  • Default: true

在和Nuxt.js集成時(shí)并發(fā)出請求時(shí)顯示加載條(只有在瀏覽器上加載條時(shí)可用)

還可以使用 progress 配置禁用每個請求的進(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'
  }
}

注意:不需要手動注冊 @nuxtjs/proxy 模塊,但它確實(shí)需要在您的依賴項(xiàng)中。

注意:將 /api 添加到API端點(diǎn)的所有請求中。如果需要刪除它,請使用 /pathRewrite

proxy: {
  '/api/': { target: 'http://api.example.com', pathRewrite: {'^/api/': ''} }
}

retry

  • Default: false
    • 自動攔截失敗的請求,并在每次使用 axios-retry 時(shí)重試它們。

默認(rèn)情況下,如果將 retry 值設(shè)置為 true,則重試次數(shù)將為3次。您可以通過傳遞這樣的對象來更改它:

axios: {
  retry: { retries: 3 }
}

credentials

  • Default: false

添加攔截器時(shí)自動設(shè)置 withCredentials,請求axios時(shí)配置 baseUrl ,允許將身份驗(yàn)證頭傳遞給后端

debug

  • Default: false

添加攔截器來記錄請求和響應(yīng)。

proxyHeaders

  • Default: true

在SSR上下文中,將客戶端請求頭設(shè)置為axios的默認(rèn)請求頭。這對于在服務(wù)器端進(jìn)行需要基于cookie的auth的請求很有用。還有助于在SSR和客戶端代碼中做出一致的請求。

注意:如果在受CloudFlare CDN保護(hù)的URL上請求,則應(yīng)將其設(shè)置為false,以防止CloudFlare錯誤地檢測到反向代理循環(huán)并返回403錯誤。

proxyHeadersIgnore

  • Default: ['host', 'accept']

只有在 proxyHeaders 設(shè)置為true 時(shí)才有效。將不需要的請求標(biāo)頭移除到SSR中的API后端。

附加問題時(shí)間:2019-10-9

問題一:很多才接觸的小伙伴不知道怎樣在js文件中使用$axios
答:普通js文件需要在plugins插件目錄中添加一個.js文件,然后在nuxt.config.js插件配置中添加該插件
示例:
plugins目錄添加的
.js

export default (context, inject) => {
  // context.$axios 獲取axios
}

nuxt.config.js Nuxt配置文件

plugins: [
  '~plugins/**',
 '~plugins/**'
]

鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容