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

📦 Axios Module

Secure and Easy Axios integration with Nuxt.js.






















✅ Features

✓ Automatically set base URL for client & server side

✓ Exposes setToken function to $axios so we can easily and globally set authentication tokens

✓ Automatically enables withCredentials when requesting to base URL

✓ Proxy request headers in SSR (Useful for auth)

✓ Fetch Style requests

✓ Integrated with Nuxt.js Progressbar while making requests

✓ Integrated with Proxy Module

✓ Auto retry requests with axios-retry

Setup

Install with yarn:

yarn add @nuxtjs/axios

Install with npm:

npm install @nuxtjs/axios

nuxt.config.js

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

axios: {
// proxyHeaders: false
}
}

Usage

Component

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)
}
}
}

Extending Axios

If you need to customize axios by registering interceptors and changing global config, you have to create a 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')
}
})
}

Helpers

Interceptors

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 Style requests

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 instance has a helper to easily set any header.

Parameters:

  • 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 instance has an additional helper to easily set global authentication header.

Parameters:

  • token: Authorization token
  • type: Authorization token prefix(Usually Bearer).
  • 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.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)

Options

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

prefix, host and port

This options are used for default values of baseURL and browserBaseURL.

Can be customized with API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) environment variables.

Default value of prefix is /.

baseURL

  • Default: http://[HOST]:[PORT][PREFIX]

Base URL which is used and prepended to make requests in server side.

Environment variable API_URL can be used to override baseURL.

browserBaseURL

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

Base URL which is used and prepended to make requests in client side.

Environment variable API_URL_BROWSER can be used to override browserBaseURL.

https

  • Default: false

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

progress

  • Default: true

Integrate with Nuxt.js progress bar to show a loading bar while making requests. (Only on browser, when loading bar is available.)

You can also disable progress bar per request using progress config.

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