Skip to content

Commit

Permalink
update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
pooya parsa committed Apr 9, 2019
1 parent 9e440c6 commit 664e074
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 128 deletions.
10 changes: 2 additions & 8 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,20 @@ module.exports = {
displayAllHeaders: true,
sidebar: [
{
title: 'Guide',
collapsable: false,
children: [
'/',
'setup',
'usage',
'options',
'helpers',
'hooks',
'advanced',
'migration'
]
}
],
nav: [
{
text: 'Guide',
link: '/'
},
{
text: 'Release notes',
text: 'Release Notes',
link: 'https://github.com/nuxt/http/blob/dev/CHANGELOG.md'
}
]
Expand Down
101 changes: 101 additions & 0 deletions docs/advanced.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Advanced

## Hooks

Sometimes we want to globally intercept HTTP request and responses.
for example display a toast on error or log them or dynamically modify requests.

HTTP module provides helpers to register hooks for request lifecycle:

- `onRequest(config)`
- `onResponse(response)`
- `onError(err)` (`err.response` may be available on response errors)

These functions don't have to return anything by default.

### Register Hooks

For registering hooks, you have to create a nuxt plugin:

**nuxt.config.js**

```js
{
modules: [
'@nuxt/http',
],

plugins: [
'~/plugins/http'
]
}
```

**plugins/http.js**

```js
export default function ({ $http }) {
$http.onRequest(config => {
console.log('Making request to ' + config.url)
})

$http.onError(error => {
if(error.response.status === 500) {
alert('Request Error!')
}
})
}
```

## Header Helpers

### `setHeader(name, value)`

Globally set a header to all subsequent requests.

> NOTE: This method should not be called inside hooks as it is global
Parameters:

* **name**: Name of the header
* **value**: Value of the header

```js
// Add header `Authorization: 123` to all requests
this.$http.setHeader('Authorization', '123')

// Override `Authorization` header with new value
this.$http.setHeader('Authorization', '456')

// Add header `Content-Type: application/x-www-form-urlencoded`
this.$http.setHeader('Content-Type', 'application/x-www-form-urlencoded')

// Remove default Content-Type header
this.$http.setHeader('Content-Type', false)
```

### `setToken(token, type)`

Globally set `Authorization` header to all subsequent requests.

Parameters:

* **token**: Authorization token
* **type**: Authorization token prefix, usually `Bearer`. Defaults to nothing

```js
// Adds header: `Authorization: 123` to all requests
this.$http.setToken('123')

// Overrides `Authorization` header with new value
this.$http.setToken('456')

// Adds header: `Authorization: Bearer 123` to all requests
this.$http.setToken('123', 'Bearer')

// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$http.setToken('123', 'Bearer', ['post', 'delete'])

// Removes default Authorization header
this.$http.setToken(false)
```
64 changes: 0 additions & 64 deletions docs/helpers.md

This file was deleted.

47 changes: 0 additions & 47 deletions docs/hooks.md

This file was deleted.

8 changes: 4 additions & 4 deletions docs/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ If you are migrating from [axios-module](https://github.com/nuxt-community/axios
- There is no scope for `setHeader`, `setToken`. Scope is common which means being applied to all requests.
- `onRequestError` and `onResponseError` hooks removed. Use `onError` instead.
- `debug` option has been removed. You can setup a basic logger using `onRequest` hook.
- The is no longer progressbar integration due to the lack of support from `fetch` spec. This option may be back after KY support of [`onProgress`](https://github.com/sindresorhus/ky/pull/34)
- The is no longer progress bar integration due to the lack of support from `fetch` spec. This option may be back after KY support of [`onProgress`](https://github.com/sindresorhus/ky/pull/34)

This module is using [ky](https://github.com/sindresorhus/ky) amd [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). There are breaking changes for usage and making requests.

## Parsing response body

Despite axios, you have to call specific methods to parse reponse body.
Despite axios that does this automatically, you have to call specific methods to parse reponse body.

```diff
-- const resJson = await this.$axios.get('/url')
++ const resJson = await this.$http.get('/url').json()
```

There is also a shortcut for JSOn by using `$` prefix on request method name.
There is also a shortcut for JSON by using `$` prefix on request method name.

```js
const resJson = await this.$http.$get('/url')
Expand All @@ -34,7 +34,7 @@ Supported response types:

## Sending requests with body

Despire axios, fetch and ky always accept **two** arguments for making requests (input and options) and you have to pass request body as options:
Despire axios, fetch and ky always accept **two** arguments for making requests (input and options). You have to pass request body in options:

For plain data or `Body`:

Expand Down
12 changes: 10 additions & 2 deletions docs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

HTTP module for Nuxt.js provides a universal way to make HTTP requests to the API backend.

This module is a successor of [Axios Module](https://github.com/nuxt-community/axios-module) with more than 100K weekly downloads and heavily tested.
This module is a successor of [Axios Module](https://github.com/nuxt-community/axios-module) and behind the scenes use [ky-universal](https://github.com/sindresorhus/ky-universal) and [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make HTTP requests. Please see [migration guide](./migration) if currently using axios module.

Starting with v2.5.0, Nuxt.js has built-in support for universal fetch. Using this module has serveral advantages and is mondatory in most of real-world use cases.

- Fluent [ky](https://github.com/sindresorhus/ky) API with more enhancenments and shortcuts
- Highly customizable options support for BaseURL
- Automatically proxy cookies and headers when making requests from server side
- Best practices to avoid token sharing while making server side requests
- Easy proxy support to avoid CORS problems and making deployment easier


Behind the scenes HTTP uses [ky-universal](https://github.com/sindresorhus/ky-universal) and [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make HTTP requests.
59 changes: 56 additions & 3 deletions docs/usage.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,59 @@
# Usage

## Page Components
## Making Requests

Available HTTP methods:

- `get`
- `post`
- `put`
- `patch`
- `head`
- `delete`

For making a request use `$http.<method>(<url>, <options>)`. Returns a Promise that either rejects in case of network errors or resolves to a [Reponse](https://developer.mozilla.org/en-US/docs/Web/API/Response) object. You can use methods to convert response stream into usable data:

- `json`
- `text`
- `formData`
- `arrayBuffer`
- `blob`

**Example: Fetch a json file**

```js
await $http.get('https://unpkg.com/nuxt/package.json').json()
```

Alternatively for json only you can use `$` prefixed shortcut:

```js
await $http.$get('https://unpkg.com/nuxt/package.json')
```

See [ky](https://github.com/sindresorhus/ky) docs for all available options.

### Sending Body

For sending body alongside with request, you can use either `json` or `body` options.
`json` is a shortcut that serializes object using `JSON.stringify` and also sets appreciate `content-type` header.

**Example: Post with JSON body**

```js
await $http.post('http://api.con', { json: { foo: 'bar' }})
```

**Example: Post with FormData body**

```js
const data = new FormData()
data.append('name', 'foo')

await $http.post('http://api.com/submit', { data })
```

## Using in `asyncData`

For `asyncData` and `fetch` you can access instance from context:

Expand All @@ -11,7 +64,7 @@ async asyncData({ $http }) {
}
```

## Component methods
## Using in Component Methods

Where you have access to `this`, you can use `this.$http`:

Expand All @@ -24,7 +77,7 @@ methods: {
}
```

## Store
## Using in Store

For store action you can also use `this.$http`:

Expand Down

0 comments on commit 664e074

Please sign in to comment.