docs: basic migration from axios to http

master
pooya parsa 2019-03-24 00:03:48 +04:30
parent b8354720f4
commit e01118631b
12 changed files with 68 additions and 89 deletions

View File

@ -1,7 +1,7 @@
<!--
IMPORTANT: Please use the following link to create a new issue:
https://cmty.app/nuxt/issues/new?repo=axios-module
https://cmty.app/nuxt/issues/new?repo=http-module
If your issue was not created using the app above, it will be closed immediately.
-->

View File

@ -7,25 +7,7 @@
[![Dependencies][david-dm-src]][david-dm-href]
[![Standard JS][standard-js-src]][standard-js-href]
TODO
## ✅ 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)
✓ Integrated with Nuxt.js Progressbar while making requests (TODO)
✓ Integrated with [Proxy Module](https://github.com/nuxt-community/proxy-module)
✓ Auto retry requests
📖 [**Read Documentation**](https://http.nuxtjs.org) (TODO)
📖 [**Read Documentation**](https://http.nuxtjs.org)
## Development

View File

@ -1,12 +1,10 @@
# 📦 Axios Module
> Secure and Easy [Axios](https://github.com/mzabriskie/axios) integration with Nuxt.js.
# HTTP Module
## Features
✓ Automatically set base URL for client & server side
✓ Exposes `setToken` function to `$axios` so we can easily and globally set authentication tokens
✓ Exposes `setToken` function to `$http` so we can easily and globally set authentication tokens
✓ Automatically enables `withCredentials` when requesting to base URL
@ -18,13 +16,13 @@
✓ Integrated with [Proxy Module](https://github.com/nuxt-community/proxy-module)
✓ Auto retry requests with [axios-retry](https://github.com/softonic/axios-retry)
✓ Auto retry requests with [http-retry](https://github.com/softonic/http-retry)
## Links
* [GitHub](https://github.com/nuxt/http-module)
* [Release Notes](./CHANGELOG.md)
* [Migration Guide](migration.md)
* [Examples](https://axios.nuxtjs.org/usage.html)
* [Examples](https://http.nuxtjs.org/usage.html)
> 👉 To get started head to [Setup](setup.md) section.

View File

@ -2,7 +2,7 @@
* [Setup](setup.md)
* [Usage](usage.md)
* [Extending axios](extend.md)
* [Extending http](extend.md)
* [Helpers](helpers.md)
* [Options](options.md)
* [Migration Guide](migration.md)

View File

@ -1,6 +1,6 @@
## Extending Axios
## Extending HTTP
If you need to customize axios by registering interceptors and changing global config, you have to create a nuxt plugin.
If you need to customize http by registering interceptors and changing global config, you have to create a nuxt plugin.
**nuxt.config.js**
@ -11,20 +11,20 @@ If you need to customize axios by registering interceptors and changing global c
],
plugins: [
'~/plugins/axios'
'~/plugins/http'
]
}
```
**plugins/axios.js**
**plugins/http.js**
```js
export default function ({ $axios, redirect }) {
$axios.onRequest(config => {
export default function ({ $http, redirect }) {
$http.onRequest(config => {
console.log('Making request to ' + config.url)
})
$axios.onError(error => {
$http.onError(error => {
const code = parseInt(error.response && error.response.status)
if (code === 400) {
redirect('/400')

View File

@ -2,7 +2,7 @@
### Interceptors
Axios plugin provides helpers to register axios interceptors easier and faster.
HTTP plugin provides helpers to register http interceptors easier and faster.
- `onRequest(config)`
- `onResponse(response)`
@ -12,11 +12,11 @@ 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`)
Example: (`plugins/http.js`)
```js
export default function ({ $axios, redirect }) {
$axios.onError(error => {
export default function ({ $http, redirect }) {
$http.onError(error => {
if(error.response.status === 500) {
redirect('/sorry')
}
@ -26,19 +26,19 @@ export default function ({ $axios, redirect }) {
### Fetch Style requests
Axios plugin also supports fetch style requests with `$` prefixed methods:
HTTP plugin also supports fetch style requests with `$` prefixed methods:
```js
// Normal usage with axios
let data = (await $axios.get('...')).data
// Normal usage with http
let data = (await $http.get('...')).data
// Fetch Style
let data = await $axios.$get('...')
let data = await $http.$get('...')
```
### `setHeader(name, value, scopes='common')`
Axios instance has a helper to easily set any header.
HTTP instance has a helper to easily set any header.
Parameters:
@ -51,23 +51,23 @@ Parameters:
```js
// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')
this.$http.setHeader('Authorization', '123')
// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')
this.$http.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', [
this.$http.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
'post'
])
// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])
this.$http.setHeader('Content-Type', false, ['post'])
```
### `setToken(token, type, scopes='common')`
Axios instance has an additional helper to easily set global authentication header.
HTTP instance has an additional helper to easily set global authentication header.
Parameters:
@ -80,17 +80,17 @@ Parameters:
```js
// Adds header: `Authorization: 123` to all requests
this.$axios.setToken('123')
this.$http.setToken('123')
// Overrides `Authorization` header with new value
this.$axios.setToken('456')
this.$http.setToken('456')
// Adds header: `Authorization: Bearer 123` to all requests
this.$axios.setToken('123', 'Bearer')
this.$http.setToken('123', 'Bearer')
// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])
this.$http.setToken('123', 'Bearer', ['post', 'delete'])
// Removes default Authorization header from `common` scope (all requests)
this.$axios.setToken(false)
this.$http.setToken(false)
```

View File

@ -1,6 +1,6 @@
## Options
You can pass options using module options or `axios` section in `nuxt.config.js`
You can pass options using module options or `http` section in `nuxt.config.js`
### `prefix`, `host` and `port`
@ -43,14 +43,14 @@ Integrate with Nuxt.js progress bar to show a loading bar while making requests.
You can also disable progress bar per request using `progress` config.
```js
this.$axios.$get('URL', { progress: false })
this.$http.$get('URL', { progress: false })
```
### `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.
You can easily integrate HTTP with [Proxy Module](https://github.com/nuxt-community/proxy-module) and is much recommended to prevent CORS and deployment problems.
**nuxt.config.js**
@ -60,7 +60,7 @@ You can easily integrate Axios with [Proxy Module](https://github.com/nuxt-commu
'@nuxt/http'
],
axios: {
http: {
proxy: true // Can be also an object with default options
},
@ -85,12 +85,12 @@ proxy: {
* Default: `false`
Automatically intercept failed requests and retries them whenever posible using [axios-retry](https://github.com/softonic/axios-retry).
Automatically intercept failed requests and retries them whenever posible using [http-retry](https://github.com/softonic/http-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: {
http: {
retry: { retries: 3 }
}
```
@ -99,7 +99,7 @@ axios: {
* Default: `false`
Adds an interceptor to automatically set `withCredentials` config of axios when requesting to `baseURL`
Adds an interceptor to automatically set `withCredentials` config of http when requesting to `baseURL`
which allows passing authentication headers to backend.
### `debug`
@ -112,7 +112,7 @@ Adds interceptors to log request and responses.
* Default: `true`
In SSR context, sets client request header as axios default request headers.
In SSR context, sets client request header as http 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.

View File

@ -21,7 +21,7 @@ module.exports = {
'@nuxt/http',
],
axios: {
http: {
// proxyHeaders: false
}
}

View File

@ -5,8 +5,8 @@
**`asyncData`**
```js
async asyncData({ $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
async asyncData({ $http }) {
const ip = await $http.$get('http://icanhazip.com')
return { ip }
}
```
@ -16,7 +16,7 @@ async asyncData({ $axios }) {
```js
methods: {
async fetchSomething() {
const ip = await this.$axios.$get('http://icanhazip.com')
const ip = await this.$http.$get('http://icanhazip.com')
this.ip = ip
}
}
@ -29,7 +29,7 @@ methods: {
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
const ip = await this.$http.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}

View File

@ -1,7 +1,7 @@
<template>
<div>
<div>session-{{ axiosSessionId }}</div>
<div>encoding-${{ axiosEncoding }}$</div>
<div>session-{{ httpSessionId }}</div>
<div>encoding-${{ httpEncoding }}$</div>
</div>
</template>
@ -11,11 +11,11 @@ let reqCtr = 1
export default {
computed: {
axiosSessionId() {
httpSessionId() {
return this.$http._defaults.headers.sessionId
},
axiosEncoding() {
httpEncoding() {
return this.$http._defaults.headers['Accept-Encoding']
}
},

33
types/index.d.ts vendored
View File

@ -1,35 +1,34 @@
import { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import Vue from 'vue'
import './vuex'
interface NuxtAxiosInstance extends AxiosInstance {
$request<T = any>(config: AxiosRequestConfig): Promise<T>
$get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>
$delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>
$head<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>
$options<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>
$post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>
$put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>
$patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>
interface NuxtHTTPInstance {
$request<T = any>(config: any): Promise<T>
$get<T = any>(url: string, config?: any): Promise<T>
$delete<T = any>(url: string, config?: any): Promise<T>
$head<T = any>(url: string, config?: any): Promise<T>
$options<T = any>(url: string, config?: any): Promise<T>
$post<T = any>(url: string, data?: any, config?: any): Promise<T>
$put<T = any>(url: string, data?: any, config?: any): Promise<T>
$patch<T = any>(url: string, data?: any, config?: any): Promise<T>
setHeader(name: string, value?: string | false, scopes?: string | string[]): void
setToken(token: string | false, type?: string, scopes?: string | string[]): void
onRequest(callback: (config: AxiosRequestConfig) => void): void
onResponse<T = any>(callback: (response: AxiosResponse<T>) => void): void
onError(callback: (error: AxiosError) => void): void
onRequestError(callback: (error: AxiosError) => void): void
onResponseError(callback: (error: AxiosError) => void): void
onRequest(callback: (config: any) => void): void
onResponse<T = any>(callback: (response: any) => void): void
onError(callback: (error: any) => void): void
onRequestError(callback: (error: any) => void): void
onResponseError(callback: (error: any) => void): void
}
declare module '@nuxt/vue-app' {
interface Context {
$axios: NuxtAxiosInstance
$http: NuxtHTTPInstance
}
}
declare module 'vue/types/vue' {
interface Vue {
$axios: NuxtAxiosInstance
$http: NuxtHTTPInstance
}
}

4
types/vuex.d.ts vendored
View File

@ -1,7 +1,7 @@
import { NuxtAxiosInstance } from '.'
import { NuxtHTTPInstance } from '.'
declare module 'vuex' {
interface Store<S> {
$axios: NuxtAxiosInstance,
$http: NuxtHTTPInstance,
}
}