docs: improve documentation (#6)

master
Pim 2019-04-10 12:10:03 +02:00 committed by Pooya Parsa
parent 3949c447f3
commit ddf313d2d8
10 changed files with 327 additions and 187 deletions

View File

@ -5,22 +5,29 @@ module.exports = {
repo: 'nuxt/http', repo: 'nuxt/http',
docsDir: 'docs', docsDir: 'docs',
editLinks: true, editLinks: true,
editLinkText: 'Edit this page on GitHub',
displayAllHeaders: true, displayAllHeaders: true,
sidebar: [ sidebar: [
{ {
collapsable: false, collapsable: false,
children: [ children: [
'/', '/',
'setup', '/guide/',
'usage', '/guide/usage',
'options', '/guide/advanced',
'advanced', '/guide/migration'
'migration'
] ]
} }
], ],
nav: [ nav: [
{ {
text: 'Guide',
link: '/guide/'
},
{
text: 'API',
link: '/api/'
}, {
text: 'Release Notes', text: 'Release Notes',
link: 'https://github.com/nuxt/http/blob/dev/CHANGELOG.md' link: 'https://github.com/nuxt/http/blob/dev/CHANGELOG.md'
} }

219
docs/api/readme.md Normal file
View File

@ -0,0 +1,219 @@
---
sidebar: auto
---
# API Reference
:::tip Note
When a method `resolves` instead of `returns` the method is async and returns a Promise
:::
## Options
You can pass options using module options or `http` section in `nuxt.config.js`
```js
{
http: {
// HTTP options here
}
}
```
### `prefix`
### `host`
### `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`.
:::tip Note
`baseURL` and `proxy` won't work together, you will need to use [`prefix`](/api/#prefix) instead
:::
### `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://`.
### `proxy`
* Default: `false`
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**
```js
{
modules: [
'@nuxt/http'
],
http: {
proxy: true // Can be also an object with default options
},
proxy: {
'/api/': 'http://api.example.com',
'/api2/': 'http://api.another-website.com'
}
}
```
:::tip Note
It is not required to manually register `@nuxtjs/proxy` module, but it does need to be in your dependencies
:::
:::tip 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 retry before failing.
By default, number of retries will be **2 times**, if `retry` value is set to `true`. You can change it by passing an object like this:
```js
http: {
retry: 1
}
```
### `proxyHeaders`
* Default: `true`
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.
:::tip Note
When 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.
## Methods
### `setHeader`
- arguments: `(name, value)`
Globally set a header to all subsequent requests
See [here](/advanced.html#header-helpers) for usage info
### `setToken`
- arguments: `(token, type)`
Globally set a `Authorization` header for all subsequent requests
See [here](/advanced.html#settoken-token-type) for usage info
## Hooks
The `arguments` listed below are those your hook will receive when it's called
### `onRequest`
- arguments: `(config)`
See [here](/advanced.html#hooks) for usage info
### `onResponse`
- arguments: `(response)`
See [here](/advanced.html#hooks) for usage info
### `onError`
- arguments: `(error)`
If the error originated from a request, the property `err.response` might be available
See [here](/advanced.html#hooks) for usage info
## HTTP Methods
:::tip Usage
See [here](/usage.html#making-requests) for usage information for below methods
:::
### `delete`
### `get`
### `head`
- arguments: `(url, options?)`
- resolves: [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response)
- rejects: `Error`
These methods corresponds to the similar named HTTP/1.1 methods
### `patch`
### `post`
### `put`
- arguments: `(url, body?, options?)`
- resolves: [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response)
- rejects: `Error`
These methods corresponds to the similar named HTTP/1.1 methods
### `$delete`
### `$get`
### `$head`
- arguments: `(url, options?)`
- resolves: `JSON`
- rejects: `Error`
These `$`-prefixed convenience methods always return the requested content as [`JSON`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json)
### `$patch`
### `$post`
### `$put`
- arguments: `(url, body?, options?)`
- resolves: `JSON`
- rejects: `Error`
These `$`-prefixed convenience methods always return the requested content as [`JSON`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json)

View File

@ -2,14 +2,9 @@
## Hooks ## Hooks
Sometimes we want to globally intercept HTTP request and responses. Hooks can be used to globally intercept HTTP request and responses. E.g. if you wish to log errors, display a toast on error or need to dynamically modify requests.
for example display a toast on error or log them or dynamically modify requests.
HTTP module provides helpers to register hooks for request lifecycle: See the [API reference](/api/#hooks) for the list of lifecycle hooks the HTTP module provides
- `onRequest(config)`
- `onResponse(response)`
- `onError(err)` (`err.response` may be available on response errors)
These functions don't have to return anything by default. These functions don't have to return anything by default.
@ -53,7 +48,9 @@ export default function ({ $http }) {
Globally set a header to all subsequent requests. Globally set a header to all subsequent requests.
> NOTE: This method should not be called inside hooks as it is global :::warning
This method should probably not be called inside hooks as it is global and will apply to all future requests
:::
Parameters: Parameters:
@ -78,6 +75,10 @@ this.$http.setHeader('Content-Type', false)
Globally set `Authorization` header to all subsequent requests. Globally set `Authorization` header to all subsequent requests.
:::tip Note
This is a global method, you only have to call it once after which all future requests will include the token
:::
Parameters: Parameters:
* **token**: Authorization token * **token**: Authorization token

42
docs/guide/migration.md Normal file
View File

@ -0,0 +1,42 @@
# Migration Guide
This guide will help you to migrate from [Axios Module](https://github.com/nuxt-community/axios-module).
:::tip Note
The nuxt-community axios module is still supported and maintained. The HTTP module uses newer web technologies like fetch which might be beneficial
:::
## Differences
- There is no scope for [`setHeader`](/api/#setheader), [`setToken`](/api/#settoken)<br/>
_When calling these methods they apply to the global scope and are used for all future requests_
- The axios hooks `onRequestError` and `onResponseError` are unified<br/>
_Use the [`onError`](/api/#onerror) hook instead_
- The http module does not have a `debug` option like the axios module<br/>
_You can setup a basic logger using the [`onRequest`](/api/#onrequest) hook_
- Progress bar integration is not supported (for the moment)<br/>
_This option may be added again once [`PR #34: Add 'onProgress' option`](https://github.com/sindresorhus/ky/pull/34) for ky is merged_
## Response body parsing
Axios automatically transforms response bodies to JSON, if you wish to keep that behaviour you will
- either need to switch to using the `$` prefixed methods
```diff
-- const resJson = await this.$axios.get('/url')
++ const resJson = await this.$http.$get('/url')
```
- or explicitly call [`json`](https://developer.mozilla.org/en-US/docs/Web/API/Body/json) on the Response:
```diff
-- const resJson = await this.$axios.get('/url')
++ const resJson = await this.$http.get('/url').json()
```
If you are already using `$` prefixed shortcuts for making requests that return JSON, you can keep using them.
```diff
-- const resJson = await this.$axios.$get('/url')
++ const resJson = await this.$http.$get('/url')
```

32
docs/guide/readme.md Normal file
View File

@ -0,0 +1,32 @@
# Setup
Check the [Nuxt.js documentation](https://nuxtjs.org/api/configuration-modules#the-modules-property) for more information about installing and using modules in Nuxt.js
## Install
Install with yarn:
```bash
yarn add @nuxt/http
```
Install with npm:
```bash
npm install @nuxt/http
```
## Configure
Add a `http` object to your **nuxt.config.js** to configure global options which will be applied to all requests
```js
module.exports = {
modules: [
'@nuxt/http',
],
http: {
// proxyHeaders: false
}
}
```

View File

@ -2,16 +2,9 @@
## Making Requests ## Making Requests
Available HTTP methods: See the [API reference](/api/#http-methods) for a list of available HTTP methods
- `get(url, options?)` Calling a HTTP methods returns a Promise that resolves to a [Reponse](https://developer.mozilla.org/en-US/docs/Web/API/Response) object or rejects in case of network errors.
- `head(url, options?)`
- `delete(url, options?)`
- `post(url, body?, options?)`
- `put(url, body?, options?)`
- `patch(url, body?, options?)`
Calling these methods, returns a Promise that resolves to a [Reponse](https://developer.mozilla.org/en-US/docs/Web/API/Response) object or rejects in case of network errors.
You can use methods to convert response stream into usable data: You can use methods to convert response stream into usable data:
@ -54,7 +47,11 @@ async asyncData({ $http }) {
## Using in Component Methods ## Using in Component Methods
Where you have access to `this`, you can use `this.$http`: :::warning Note
`this` is not available in Nuxt's `asyncData` method, see [here](/usage.html#using-in-asyncdata) for how to use this module in `asyncData`
:::
When you have access to `this`, you can use `this.$http`:
```js ```js
methods: { methods: {
@ -67,7 +64,7 @@ methods: {
## Using in Store ## Using in Store
For store action you can also use `this.$http`: For store actions you can also use `this.$http`:
```js ```js
// In store // In store

View File

@ -1,23 +0,0 @@
# Migration Guide
If you are migrating from [Axios Module](https://github.com/nuxt-community/axios-module) this guide may be useful. The community axios module will be supported and maintained. HTTP uses newer web technologies like fetch.
- There is no scope for `setHeader`, `setToken`. Scope is common which means being applied to all requests.
- `onRequestError` and `onResponseError` hooks unified. Use `onError` instead.
- `debug` option has been removed. You can setup a basic logger using `onRequest` hook.
- The progress bar integration is not supported. This option may be back after ky PR for support of [`onProgress`](https://github.com/sindresorhus/ky/pull/34)
**Parsing response 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()
```
If you are using `$` prefixed shortcuts for making requests that respond JSON, you can keep using it without need to changes.
```js
const resJson = await this.$http.$get('/url')
```

View File

@ -1,108 +0,0 @@
# Options
You can pass options using module options or `http` section in `nuxt.config.js`
```js
{
http: {
// HTTP options here
}
}
```
## `prefix`, `host`, `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`.
**Note:** `baseURL` and `proxy` doesn't work together, you need to use `prefix` instead.
## `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://`.
## `proxy`
* Default: `false`
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**
```js
{
modules: [
'@nuxt/http'
],
http: {
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 retry before failing.
By default, number of retries will be **2 times**, if `retry` value is set to `true`. You can change it by passing an object like this:
```js
http: {
retry: 1
}
```
## `proxyHeaders`
* Default: `true`
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.
> **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.

View File

@ -2,12 +2,12 @@
HTTP module for Nuxt.js provides a universal way to make HTTP requests to the API backend. HTTP module for Nuxt.js provides a universal way to make HTTP requests to the API backend.
This module is an alternative 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 and want to migrate. This module is an alternative to [Axios Module](https://github.com/nuxt-community/axios-module). Behind the scenes it 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 the [migration guide](./migration) if you are currently using axios module and wish to migrate.
Starting with v2.5.0, Nuxt.js has built-in support for universal fetch, However using this module has serveral advantages: Starting from `v2.5.0`, Nuxt.js has built-in support for universal fetch. However, this module provides several advantages:
- Fluent [ky](https://github.com/sindresorhus/ky) API with more enhancenments and shortcuts - The fluent [ky](https://github.com/sindresorhus/ky) API has been extended with enhancements and shortcuts
- Highly customizable options support for BaseURL - Highly customizable options support for [`BaseURL`](/api/#baseurl)
- Automatically proxy cookies and headers when making requests from server side - Automatically proxy cookies and headers when making requests from server side
- Best practices to avoid token sharing while making server side requests - Best practices to avoid token sharing when making server side requests
- Easy proxy support to avoid CORS problems and making deployment easier - Easy proxy support to avoid CORS problems and making deployment easier

View File

@ -1,27 +0,0 @@
# Setup
Install with yarn:
```bash
yarn add @nuxt/http
```
Install with npm:
```bash
npm install @nuxt/http
```
**nuxt.config.js**
```js
module.exports = {
modules: [
'@nuxt/http',
],
http: {
// proxyHeaders: false
}
}
```