nuxtjs-axios

2020-02-07 13:25 更新
安全簡(jiǎn)單的、與 Nuxt.js 集成的 Axios。


特點(diǎn)

  • 無(wú)論是客戶端還是 server 端,自動(dòng)設(shè)置 baseURL
  • $axios對(duì)象上暴露 setToken函數(shù)方法,我們能輕而易舉的設(shè)置認(rèn)證 tokens
  • 當(dāng)請(qǐng)求發(fā)送到 baseURL 時(shí),自動(dòng)啟用 withCredentials特性
  • SSR模式下代理頭信息(Useful for auth)
  • Fetch 風(fēng)格的請(qǐng)求
  • 和 Nuxt.js 的 Progressbar 完美結(jié)合
  • 支持 Proxy Module

  • 自動(dòng)重試機(jī)制 axios-retry


安裝

使用 npm:

npm install @nuxtjs/axios

使用 yarn:

yarn add @nuxtjs/axios

nuxt.config.js

module.exports = {
    modules: [
        '@nuxtjs/axios'
    ],
    axios: {
        // proxyHeaders: false
    }
}


使用

組件

asyncData
async asyncData ({ app }) {
    const ip = await app.$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 }, { app }) {
const ip = await app.$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

如果你需要通過(guò)注冊(cè)攔截器或者改變?nèi)衷O(shè)置來(lái)定制化axios,你需要?jiǎng)?chuàng)建一個(gè)nuxt plugin。

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 plugin provides helpers to register axios interceptors easier and faster.

  • onRequest(config)
  • onResponse(response)
  • onError(err)
  • onRequestError(err)
  • onResponseError(err)

These functions don’t have to return anything by default.

Example: (plugins/axios.js)

export default function ({ $axios, redirect }) {
$axios.onError(error => {
if(error.code === 500) {
redirect('/sorry')
}
})
}

Fetch 風(fēng)格請(qǐng)求

Axios plugin also supports fetch style requests with $ prefixed methods:

// Normal usage with axios
let data = (await $axios.get('...')).data

// Fetch Style
let data = await $axios.$get('...')

setHeader(name, value, scopes='common')

Axios 對(duì)象非常方面設(shè)置header部分

參數(shù):

  • name: Name of the header
  • value: Value of the header
  • scopes: Send only on specific type of requests. DefaultsType: Array or StringDefaults to common meaning all types of requestsCan be 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'])

setToken(token, type, scopes='common')

Axios實(shí)例可以方便的設(shè)置全局頭信息

Parameters:

  • token: 認(rèn)證需要的token
  • type: 認(rèn)證token前綴(Usually Bearer).
  • scopes: 用于特定請(qǐng)求設(shè)置. DefaultsType: Array or StringDefaults to common meaning all types of requestsCan be 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)

在 nuxt.config.js 中,你可以使用模塊選項(xiàng) 或 axios section 傳遞選項(xiàng)。

prefix, host and port

用來(lái)配置 baseURL and browserBaseURL部分。

可以使用 API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) 環(huán)境變量.

prefix的默認(rèn)值是/.

baseURL

  • 默認(rèn)值: http://[HOST]:[PORT][PREFIX]

Base URL 是用于在 server side 模式下的請(qǐng)求配置.

環(huán)境變量 API_URL 可以覆蓋 override baseURL設(shè)置

browserBaseURL

  • Default: baseURL (or prefix when options.proxy is enabled)

Base URL 適用于客戶端模式下的配置.

環(huán)境變量 API_URL_BROWSER 可以覆蓋 override browserBaseURL.

https

  • 默認(rèn): false

If set to true, http:// in both baseURL and browserBaseURL will be changed into https://.

progress

  • 默認(rèn): true

和 Nuxt.js progress bar 一起用于顯示loading狀態(tài) (僅在瀏覽器上,且loading bar可用)

你可以禁止適用這項(xiàng)配置

this.$axios.$get('URL', { progress: false })

proxy

  • Default: false

你可以很容易的將 Axios 與代理模塊集成在一起,并推薦用于CORS和部署問(wè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'
}
}

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

Note:/api/將被添加到api端點(diǎn)的所有請(qǐng)求中。如果需要?jiǎng)h除,請(qǐng)使用pathrewite:

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

retry

  • Default: false

自動(dòng)攔截失敗的請(qǐng)求,并在使用 axios-retry 時(shí),對(duì)它們進(jìn)行重試。

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

axios: {
retry: { retries: 3 }
}

credentials

  • Default: false

當(dāng)請(qǐng)求到允許傳遞驗(yàn)證頭后端的基礎(chǔ)節(jié)點(diǎn)時(shí),添加一個(gè)攔截器來(lái)自動(dòng)設(shè)置AXIOS的憑據(jù)配置。

debug

  • Default: false

向日志請(qǐng)求和響應(yīng)添加偵聽(tīng)器。

proxyHeaders

  • Default: true

在SSR上下文中,將客戶端請(qǐng)求頭設(shè)置為AXIOS默認(rèn)請(qǐng)求頭。這對(duì)于在服務(wù)器端請(qǐng)求基于Cookie的Autho的請(qǐng)求是有用的。也有助于在SSR和客戶端代碼中做出一致的請(qǐng)求。

NOTE:如果將請(qǐng)求定向到受CloudFlare的CDN保護(hù)的url,則應(yīng)將此設(shè)置為false,以防止CloudFlare錯(cuò)誤地檢測(cè)到反向代理循環(huán)并返回403錯(cuò)誤。

proxyHeadersIgnore

  • Default ['host', 'accept']

只有當(dāng)proxyHeaders設(shè)置為true時(shí)才有效。刪除不需要的請(qǐng)求頭到SSR中的API后端。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)