nuxtjs-axios|axios中文网

本站由axios爱好者共建,部署在vultr vps上,推荐使用vultr!价格实惠,实力雄厚。 最近新注册用户充值$25,可额外获赠$50,搭建博客必备。 前往注册

📦 Axios 模块

Secure and Easy Axios integration with Nuxt.js.






















✅ 特点

✓ 无论是客户端还是server端,自动设置 base URL

✓ 在$axios对象上暴露 setToken函数方法, 我们能轻而易举的设置认证 tokens

✓ 自动启用 withCredentials特性 当请求发送到base URL时

✓ SSR模式下代理头信息 (Useful for auth)

✓ Fetch 风格的请求

✓ 和Nuxt.js的 Progressbar完美结合

✓ 支持 Proxy Module

✓ 自动重试机制 axios-retry



安装

使用 yarn:

yarn add @nuxtjs/axios

使用 npm:

npm install @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)
}
}
}

扩展Axios

如果你需要通过注册拦截器或者改变全局设置来定制化axios, 你需要创建一个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 风格请求

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 对象非常方面设置header部分

参数:

  • name: Name of the header
  • value: Value of the header
  • scopes: Send only on specific type of requests. Defaults
    • Type: Array or String
    • Defaults to common meaning all types of requests
    • Can 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实例可以方便的设置全局头信息

Parameters:

  • token: 认证需要的token
  • type: 认证token前缀(Usually Bearer).
  • scopes: 用于特定请求设置. Defaults
    • Type: Array or String
    • Defaults to common meaning all types of requests
    • Can 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)

选项

You can pass options using module options or axios section in nuxt.config.js

prefix, host and port

用来配置 baseURL and browserBaseURL部分。

可以使用 API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) 环境变量.

prefix的默认值是/.

baseURL

  • 默认值: http://[HOST]:[PORT][PREFIX]

Base URL 是用于在 server side 模式下的请求配置.

环境变量 API_URL 可以覆盖 override baseURL设置

browserBaseURL

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

Base URL 适用于客户端模式下的配置.

环境变量 API_URL_BROWSER 可以覆盖 override browserBaseURL.

https

  • 默认: false

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

progress

  • 默认: true

和 Nuxt.js progress bar 一起用于显示loading状态 (仅在浏览器上,且loading bar可用)

你可以禁止适用这项配置

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

proxy

  • Default: false

You can easily integrate Axios with Proxy Module and is much recommended to prevent CORS and deployment problems.

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: It is not required to manually register @nuxtjs/proxy module, but it does need to be in your dependencies.

Note: /api/ will be added to all requests to the API end point. If you need to remove it use pathRewrite:

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

retry

  • Default: false

    Automatically intercept failed requests and retries them whenever posible using axios-retry.

By default, number of retries will be 3 times, if retry value is set to true. You can change it by passing an object like this:

axios: {
retry: { retries: 3 }
}

credentials

  • Default: false

Adds an interceptor to automatically set withCredentials config of axios when requesting to baseUrl
which allows passing authentication headers to backend.

debug

  • Default: false

Adds interceptors to log request and responses.

proxyHeaders

  • Default: true

In SSR context, sets client request header as axios default request headers.
This is useful for making requests which need cookie based auth on server side.
Also helps making consistent requests in both SSR and Client Side code.

NOTE: If directing requests at a url protected by CloudFlare’s CDN you should set this to false to prevent CloudFlare from mistakenly detecting a reverse proxy loop and returning a 403 error.

proxyHeadersIgnore

  • Default ['host', 'accept']

Only efficient when proxyHeaders is set to true. Removes unwanted request headers to the API backend in SSR.

From 4.x to 5.x

BaseURL options and handling have been completely rewritten.

Please refer to the latest docs.

Default prefix is now / instead of /api.

You have to explicitly add /api/ in all requests.

credentials is now disabled by default.

For using old defaults:

{
axios: {
prefix: '/api',
credentials: true
}
}

Default error interceptor removed

All lifecycle functions removed

You can now easily use a plugin to extend axios and add your custom logic there.

Please see Extending Axios section in docs.

Change Log

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

5.3.2 (2018-09-21)

Bug Fixes

  • types: replace AxiosPromise to Promise (#162) (5fd9214)

5.3.1 (2018-03-31)

5.3.0 (2018-03-31)

Features

5.2.0 (2018-03-31)

Bug Fixes

  • progress: onProgress when currentRequests is zero (#118) (a90236e)

Features

5.1.1 (2018-03-06)

Bug Fixes

5.1.0 (2018-03-05)

Features

  • allow disable progress per request. closes #112. (1530bb6)
  • disable https for localhost url (#93) (dd67734)

5.0.1 (2018-02-08)

Bug Fixes

  • don’t mutate env.API_URL (a8ea331)

5.0.0 (2018-02-04)

Bug Fixes

  • progress: finish on fail (ea7b569)

Features

5.0.0-rc.2 (2018-01-29)

Bug Fixes

5.0.0-rc.1 (2018-01-28)

Bug Fixes

  • progress: ensure $loading is valid (cbdc586)

5.0.0-rc.0 (2018-01-28)

Features

5.0.0-alpha.1 (2018-01-28)

Features

  • integrate with nuxt progress bar (41a0964)

5.0.0-alpha.0 (2018-01-28)

Code Refactoring

  • a better and more stable way to specify baseURL and browserBaseURL options (533cf4e)

Features

BREAKING CHANGES

  • prefix should be set to /api for backward compability. refer to new docs.

4.5.2 (2017-12-29)

4.5.1 (2017-12-29)

4.5.0 (2017-11-16)

Bug Fixes

Features

4.4.0 (2017-09-30)

Features

  • proxyHeader: proxyHeadersIgnore option (7c13655)

4.3.1 (2017-09-28)

4.3.0 (2017-09-11)

Features

  • don’t rely on hostname for default values (dadd7d8)

4.2.1 (2017-09-08)

4.2.0 (2017-09-08)

Features

  • pass ctx to errorHandlers (c70749a)

4.1.1 (2017-09-06)

Bug Fixes

4.1.0 (2017-09-06)

Bug Fixes

  • inject $axios in current ctx (356b31f)

Features

Performance Improvements

  • move init outside of plugin (bcd4710)

4.0.1 (2017-09-04)

Bug Fixes

  • package: make nuxt devDependency (a36a886)

4.0.0 (2017-08-30)

Features

  • better baseURL message (61432a1)
  • responseInterceptor and errorHandler (b16d6bf)
  • upgrade for nuxt rc8 (a341185)

BREAKING CHANGES

  • app.axios is not available anymore (without $) should always use app.$axios

3.1.4 (2017-08-13)

Bug Fixes

  • create fresh objects for all default header scopes (7ba3ae8)

3.1.3 (2017-08-13)

Bug Fixes

  • headers: fix security bug with default request headers (9355228)

3.1.1 (2017-08-13)

(repository moved from nuxt-community/modules)

Features

  • axios: fetch style requests

3.0.1 (2017-07-25)

Bug Fixes

  • axios: typo in default headers (9697559)

3.0.0 (2017-07-25)

Code Refactoring

  • axios: remove $ shortcut mixins (1ab2bd6)

BREAKING CHANGES

  • axios: You have to explicitly use this.$axios.[method] instead of this.$[method]

2.3.0 (2017-07-24)

Features

  • axios: optionally disable error handling (#74) (a195feb)
  • axios: redirectError (4ce1a1c)

2.2.4 (2017-07-20)

Bug Fixes

2.2.3 (2017-07-19)

Bug Fixes

  • axios: don’t proxy Host header from request (#72, #39) (61462ca)

2.2.2 (2017-07-19)

Bug Fixes

  • axios: don’t proxy Host header from request (#72, #39) (61462ca)

2.2.1 (2017-07-15)

Bug Fixes

  • axios: problems related to #65 (4e7dd3f)

2.0.3 (2017-06-10)

Bug Fixes

  • axios: Handle relative baseURL (19b8453)
  • handle 0.0.0.0 host (610e0f5)

2.0.2 (2017-06-09)

Bug Fixes

  • axios: Node 6.x support (54deac0)

2.0.1 (2017-06-09)

Bug Fixes

  • axios: ensure store exists before injecting (23ad7b7)

2.0.0 (2017-06-09)

Bug Fixes

  • axios: install using Vue.use (184651b)
  • axios: req typo (16f28b1)
  • axios: use relative API_URL if same host and port else API_URL (3421d19)

Features

  • axios: AXIOS_CREDENTIALS, AXIOS_SSR_HEADERS (4dfdc2d)
  • axios: don’t append optional config into env (fe189e8)
  • axios: Easier API (f54a434)
  • axios: New API (0194226)
  • axios: nuxt friendly errors for SSR (65bc50f)

BREAKING CHANGES

  • axios: API_PREFIX is deprecated.

1.0.2 (2017-05-29)

Bug Fixes

  • axios: remove extra function call on computed prop (cd9da0b)

1.0.1 (2017-05-26)

Bug Fixes

  • axios: remove extra function call on computed prop (cd9da0b)

1.0.0 (2017-05-26)

Features

  • initial migration to 1.0.0-alpha1 (05c1b7a)

BREAKING CHANGES

  • New modules system is backward incompatible with nuxt-helpers style modules

0.0.1 (2017-05-10)

📑 License

MIT License - Nuxt Community