📖 docs: move to gitbook

master
Pooya Parsa 2018-02-17 19:07:27 +03:30
parent 0a1b86d2d8
commit d5d5aeb074
11 changed files with 420 additions and 1 deletions

1
.gitignore vendored
View File

@ -6,3 +6,4 @@ node_modules
.vscode
.DS_STORE
coverage
_book

27
book.json Normal file
View File

@ -0,0 +1,27 @@
{
"title": "Nuxt Axios Module",
"gitbook": ">3.0.0",
"root": "./docs",
"plugins": [
"edit-link",
"prism",
"theme-vuejs-2",
"-fontsettings",
"github"
],
"pluginsConfig": {
"edit-link": {
"base": "https://github.com/nuxt-community/axios-module/tree/master/docs",
"label": "Edit This Page"
},
"github": {
"url": "https://github.com/nuxt-community/axios-module"
}
},
"links": {
"sharing": {
"facebook": false,
"twitter": false
}
}
}

1
docs/changelog.md Symbolic link
View File

@ -0,0 +1 @@
../CHANGELOG.md

34
docs/extend.md Normal file
View File

@ -0,0 +1,34 @@
## 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**
```js
{
modules: [
'@nuxtjs/axios',
],
plugins: [
'~/plugins/axios'
]
}
```
**plugins/axios.js**
```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')
}
})
}
```

96
docs/helpers.md Normal file
View File

@ -0,0 +1,96 @@
## Helpers
### Interceptors
Axios plugin provides helpers to register axios interceptors easier and faster.
- `onRequest(config)`
- `onResponse(response)`
- `onError(err)`
- `onRequestError(err)`
- `onResponseError(err)`
This functions don't have to return anything by default.
Example: (`plugins/axios.js`)
```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:
```js
// 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`, ...
```js
// 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`, ...
```js
// 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)
```

30
docs/migration.md Normal file
View File

@ -0,0 +1,30 @@
## 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:
```js
{
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](https://github.com/nuxt-community/axios-module#extending-axios) section in docs.

117
docs/options.md Normal file
View File

@ -0,0 +1,117 @@
## 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.)
### `proxy`
* Default: `false`
You can easily integrate Axios with [Proxy Module](https://github.com/nuxt-community/proxy-module) and is much recommended to prevent CORS and deployment problems.
**nuxt.config.js**
```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`:
```js
proxy: {
'/api/': { target: 'http://api.example.com', pathRewrite: {'^/api/': ''} }
}
```
### `retry`
* Default: `false`
Automatically intercept failed requests and retries them whenever posible using [axios-retry](https://github.com/softonic/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:
```js
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.

30
docs/readme.md Normal file
View File

@ -0,0 +1,30 @@
# Axios Module
> Secure and Easy [Axios](https://github.com/mzabriskie/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](https://github.com/nuxt-community/proxy-module)
✓ Auto retry requests with [axios-retry](https://github.com/softonic/axios-retry)
## Links
* [Github](https://github.com/nuxt-community/axios-module)
* [Release Notes](./CHANGELOG.md)
* [Migration Guide](migration.md)
* [Examples](https://github.com/nuxt-community/axios-module/tree/master/examples)
> 👉 To get started head to [Setup](setup.md) section.

28
docs/setup.md Normal file
View File

@ -0,0 +1,28 @@
## Setup
Install with yarn:
```bash
yarn add @nuxtjs/axios
```
Install with npm:
```bash
npm install @nuxtjs/axios
```
**nuxt.config.js**
```js
{
modules: [
'@nuxtjs/axios',
],
axios: {
// proxyHeaders: false
}
}
```

9
docs/summary.md Normal file
View File

@ -0,0 +1,9 @@
# Summary
* [Setup](setup.md)
* [Usage](usage.md)
* [Extending axios](extend.md)
* [Helpers](helpers.md)
* [Options](options.md)
* [Migration Guide](migration.md)
* [Changelog](CHANGELOG.md)

46
docs/usage.md Normal file
View File

@ -0,0 +1,46 @@
## Usage
### Component
**`asyncData`**
```js
async asyncData({ app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
return { ip }
}
```
**`methods`/`created`/`mounted`/etc**
```js
methods: {
async fetchSomething() {
const ip = await this.$axios.$get('http://icanhazip.com')
this.ip = ip
}
}
```
### Store `nuxtServerInit`
```js
async nuxtServerInit ({ commit }, { app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
```
### Store actions
```js
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}
```