安全簡(jiǎn)單的、與 Nuxt.js 集成的 Axios。
$axios
對(duì)象上暴露 setToken
函數(shù)方法,我們能輕而易舉的設(shè)置認(rèn)證 tokens
withCredentials
特性
支持 Proxy Module
自動(dòng)重試機(jī)制 axios-retry
使用 npm:
npm install @nuxtjs/axios
使用 yarn:
yarn add @nuxtjs/axios
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
}
}
async nuxtServerInit ({ commit }, { app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}
如果你需要通過(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.
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')
}
})
}
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('...')
Axios 對(duì)象非常方面設(shè)置header部分
參數(shù):
// 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'])
Axios實(shí)例可以方便的設(shè)置全局頭信息
Parameters:
// 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)
在 nuxt.config.js 中,你可以使用模塊選項(xiàng) 或 axios section 傳遞選項(xiàng)。
用來(lái)配置 baseURL and browserBaseURL部分。
可以使用 API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) 環(huán)境變量.
prefix的默認(rèn)值是/.
Base URL 是用于在 server side 模式下的請(qǐng)求配置.
環(huán)境變量 API_URL 可以覆蓋 override baseURL設(shè)置
Base URL 適用于客戶端模式下的配置.
環(huán)境變量 API_URL_BROWSER 可以覆蓋 override browserBaseURL.
If set to true, http:// in both baseURL and browserBaseURL will be changed into https://.
和 Nuxt.js progress bar 一起用于顯示loading狀態(tài) (僅在瀏覽器上,且loading bar可用)
你可以禁止適用這項(xiàng)配置
this.$axios.$get('URL', { progress: 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/': ''} }
}
自動(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 }
}
當(dāng)請(qǐng)求到允許傳遞驗(yàn)證頭后端的基礎(chǔ)節(jié)點(diǎn)時(shí),添加一個(gè)攔截器來(lái)自動(dòng)設(shè)置AXIOS的憑據(jù)配置。
向日志請(qǐng)求和響應(yīng)添加偵聽(tīng)器。
在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ò)誤。
只有當(dāng)proxyHeaders設(shè)置為true時(shí)才有效。刪除不需要的請(qǐng)求頭到SSR中的API后端。
更多建議: