Skip to content

Commit 533cf4e

Browse files
author
Pooya Parsa
committed
refactor: a better and more stable way to specify baseURL and browserBaseURL options
BREAKING CHANGE: prefix should be set to `/api` for backward compability. refer to new docs.
1 parent 8e0ee32 commit 533cf4e

File tree

5 files changed

+158
-98
lines changed

5 files changed

+158
-98
lines changed

README.md

+107-70
Original file line numberDiff line numberDiff line change
@@ -32,47 +32,50 @@
3232

3333
# Table of Contents
3434

35-
- [Features](#features)
36-
- [Setup](#setup)
37-
- [Usage](#usage)
38-
- [Component](#component)
39-
- [Store](#store-nuxtserverinit)
40-
- [Store Actions](#store-actions)
41-
- [Options](#options)
42-
- [browserBaseURL](#browserbaseurl)
43-
- [credentials](#credentials)
44-
- [debug](#debug)
45-
- [proxyHeaders](#proxyheaders)
46-
- [proxyHeadersIgnore](#proxyheadersignore)
47-
- [redirectError](#redirecterror)
48-
- [requestInterceptor](#requestinterceptor)
49-
- [responseInterceptor](#responseinterceptor)
50-
- [init](#init)
51-
- [disableDefaultErrorHandler](#disabledefaulterrorhandler)
52-
- [errorHandler](#errorhandler)
53-
- [Helpers](#helpers)
54-
- [Fetch Style Requests](#fetch-style-requests)
55-
- [Set Header](#setheadername-value-scopescommon)
56-
- [Set Token](#settokentoken-type-scopescommon)
57-
- [Dynamic API Backend](#dynamic-api-backend)
35+
* [Features](#features)
36+
* [Setup](#setup)
37+
* [Usage](#usage)
38+
* [Component](#component)
39+
* [Store](#store-nuxtserverinit)
40+
* [Store Actions](#store-actions)
41+
* [Options](#options)
42+
* [baseURL](#baseURL)
43+
* [browserBaseURL](#browserbaseurl)
44+
* [credentials](#credentials)
45+
* [debug](#debug)
46+
* [proxyHeaders](#proxyheaders)
47+
* [proxyHeadersIgnore](#proxyheadersignore)
48+
* [redirectError](#redirecterror)
49+
* [requestInterceptor](#requestinterceptor)
50+
* [responseInterceptor](#responseinterceptor)
51+
* [init](#init)
52+
* [disableDefaultErrorHandler](#disabledefaulterrorhandler)
53+
* [errorHandler](#errorhandler)
54+
* [Helpers](#helpers)
55+
* [Fetch Style Requests](#fetch-style-requests)
56+
* [Set Header](#setheadername-value-scopescommon)
57+
* [Set Token](#settokentoken-type-scopescommon)
58+
* [Dynamic API Backend](#dynamic-api-backend)
5859

5960
## Features
6061

61-
- Automatically set base URL for client & server side
62-
- Exposes `setToken` function to `$axios` so we can easily and globally set authentication tokens
63-
- Throws *nuxt-friendly* errors and optionally redirect on specific error codes
64-
- Automatically enables `withCredentials` when requesting to base URL
65-
- Proxy request headers in SSR (Useful for auth)
66-
- Fetch Style requests
62+
* Automatically set base URL for client & server side
63+
* Exposes `setToken` function to `$axios` so we can easily and globally set authentication tokens
64+
* Throws _nuxt-friendly_ errors and optionally redirect on specific error codes
65+
* Automatically enables `withCredentials` when requesting to base URL
66+
* Proxy request headers in SSR (Useful for auth)
67+
* Fetch Style requests
6768

6869
## Setup
6970

7071
Install with npm:
72+
7173
```bash
7274
>_ npm install @nuxtjs/axios
7375
```
7476

7577
Install with yarn:
78+
7679
```bash
7780
>_ yarn add @nuxtjs/axios
7881
```
@@ -93,7 +96,7 @@ Install with yarn:
9396

9497
## Usage
9598

96-
### Component
99+
### Component
97100

98101
**`asyncData`**
99102

@@ -116,6 +119,7 @@ methods: {
116119
```
117120

118121
### Store `nuxtServerInit`
122+
119123
```js
120124
async nuxtServerInit ({ commit }, { app }) {
121125
const ip = await app.$axios.$get('http://icanhazip.com')
@@ -124,6 +128,7 @@ async nuxtServerInit ({ commit }, { app }) {
124128
```
125129

126130
### Store actions
131+
127132
(Needs Nuxt >= 1.0.0-RC8)
128133

129134
```js
@@ -139,37 +144,49 @@ async nuxtServerInit ({ commit }, { app }) {
139144
```
140145

141146
## Options
142-
You can pass options using module options or `axios` section in `nuxt.config.js`
147+
148+
You can pass options using module options or `axios` section in `nuxt.config.js`
149+
150+
### `prefix`, `host` and `port`
151+
152+
This options are used for default values of `baseURL` and `browserBaseURL`.
153+
154+
Can be customized with `API_PREFIX`, `API_HOST` (or `HOST`) and `API_PORT` (or `PORT`) environment variables too.
155+
156+
Default value of `prefix` is `/`.
143157

144158
### `baseURL`
145-
- Default: `http://[HOST]:[PORT]/api`
146159

147-
Base URL is required for requests in server-side & SSR and prepended to all requests with relative path.
148-
You can also use environment variable `API_URL` which **overrides** `baseURL`.
160+
* Default: `http://[HOST]:[PORT][PREFIX]`
161+
162+
Base URL is required for requests in server-side & SSR and prepended to all axios requests.
163+
164+
Environment variable `API_URL` can be used to **override** `baseURL`.
149165

150166
### `browserBaseURL`
151-
- Default: `/api`
152167

153-
Base URL which is used in client side prepended to all requests with relative path.
154-
You can also use environment variable `API_URL_BROWSER` which **overrides** `browserBaseURL`.
168+
* Default: `baseURL` (or `prefix` when `options.proxyMode` is `true`)
169+
170+
Base URL which is used in client side and prepended to all axios requests.
155171

156-
- If `browserBaseURL` is not provided it defaults to `baseURL` value.
157-
- If hostname & port of `browserbaseURL` are equal to nuxt server, it defaults to relative part of `baseURL`.
158-
So if your nuxt application is being accessed under a different domain, requests go to same origin and prevents Cross-Origin problems.
172+
Environment variable `API_URL_BROWSER` can be used to **override** `browserBaseURL`.
159173

160174
### `credentials`
161-
- Default: `true`
175+
176+
* Default: `true`
162177

163178
Adds an interceptor to automatically set `withCredentials` config of axios when requesting to `baseUrl`
164179
which allows passing authentication headers to backend.
165180

166181
### `debug`
167-
- Default: `false`
182+
183+
* Default: `false`
168184

169185
Adds interceptors to log all responses and requests
170186

171187
### `proxyHeaders`
172-
- Default: `true`
188+
189+
* Default: `true`
173190

174191
In SSR context, sets client request header as axios default request headers.
175192
This is useful for making requests which need cookie based auth on server side.
@@ -178,15 +195,18 @@ Also helps making consistent requests in both SSR and Client Side code.
178195
> **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.
179196
180197
### `proxyHeadersIgnore`
181-
- Default `['host', 'accept']`
198+
199+
* Default `['host', 'accept']`
182200

183201
Only efficient when `proxyHeaders` is set to true. Removes unwanted request headers to the API backend in SSR.
184202

185203
### `redirectError`
186-
- Default: `{}`
204+
205+
* Default: `{}`
187206

188207
This option is a map from specific error codes to page which they should be redirect.
189208
For example if you want redirecting all `401` errors to `/login` use:
209+
190210
```js
191211
axios: {
192212
redirectError: {
@@ -196,7 +216,8 @@ axios: {
196216
```
197217

198218
### `requestInterceptor`
199-
- Default: `null`
219+
220+
* Default: `null`
200221

201222
Function for manipulating axios requests. Useful for setting custom headers,
202223
for example based on the store state. The second argument is the nuxt context.
@@ -211,19 +232,20 @@ requestInterceptor: (config, { store }) => {
211232
```
212233

213234
### `responseInterceptor`
214-
- Default: `null`
235+
236+
* Default: `null`
215237

216238
```js
217239
responseInterceptor: (response, ctx) => {
218240
return response
219241
}
220242
```
221243

222-
223244
Function for manipulating axios responses.
224245

225246
### `init`
226-
- Default: `null`
247+
248+
* Default: `null`
227249

228250
Function `init(axios, ctx)` to do additional things with axios. Example:
229251

@@ -236,13 +258,15 @@ axios: {
236258
```
237259

238260
### `disableDefaultErrorHandler`
239-
- Default: `false`
261+
262+
* Default: `false`
240263

241264
If you want to disable the default error handler for some reason, you can do it so
242265
by setting the option `disableDefaultErrorHandler` to true.
243266

244267
### `errorHandler`
245-
- Default: (Return promise rejection with error)
268+
269+
* Default: (Return promise rejection with error)
246270

247271
Function for custom global error handler.
248272
This example uses nuxt default error page.
@@ -260,7 +284,9 @@ axios: {
260284
## Helpers
261285

262286
### Fetch Style requests
287+
263288
Axios plugin also supports fetch style requests with `$` prefixed methods:
289+
264290
```js
265291
// Normal usage with axios
266292
let data = (await $axios.get('...')).data
@@ -270,15 +296,17 @@ let data = await $axios.$get('...')
270296
```
271297

272298
### `setHeader(name, value, scopes='common')`
299+
273300
Axios instance has a helper to easily set any header.
274301

275302
Parameters:
276-
- **name**: Name of the header
277-
- **value**: Value of the header
278-
- **scopes**: Send only on specific type of requests. Defaults
279-
- Type: *Array* or *String*
280-
- Defaults to `common` meaning all types of requests
281-
- Can be `get`, `post`, `delete`, ...
303+
304+
* **name**: Name of the header
305+
* **value**: Value of the header
306+
* **scopes**: Send only on specific type of requests. Defaults
307+
* Type: _Array_ or _String_
308+
* Defaults to `common` meaning all types of requests
309+
* Can be `get`, `post`, `delete`, ...
282310

283311
```js
284312
// Adds header: `Authorization: 123` to all requests
@@ -288,22 +316,26 @@ this.$axios.setHeader('Authorization', '123')
288316
this.$axios.setHeader('Authorization', '456')
289317

290318
// Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests
291-
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', ['post'])
319+
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
320+
'post'
321+
])
292322

293323
// Removes default Content-Type header from `post` scope
294324
this.$axios.setHeader('Content-Type', false, ['post'])
295325
```
296326

297327
### `setToken(token, type, scopes='common')`
328+
298329
Axios instance has an additional helper to easily set global authentication header.
299330

300331
Parameters:
301-
- **token**: Authorization token
302-
- **type**: Authorization token prefix(Usually `Bearer`).
303-
- **scopes**: Send only on specific type of requests. Defaults
304-
- Type: *Array* or *String*
305-
- Defaults to `common` meaning all types of requests
306-
- Can be `get`, `post`, `delete`, ...
332+
333+
* **token**: Authorization token
334+
* **type**: Authorization token prefix(Usually `Bearer`).
335+
* **scopes**: Send only on specific type of requests. Defaults
336+
* Type: _Array_ or _String_
337+
* Defaults to `common` meaning all types of requests
338+
* Can be `get`, `post`, `delete`, ...
307339

308340
```js
309341
// Adds header: `Authorization: 123` to all requests
@@ -323,6 +355,7 @@ this.$axios.setToken(false)
323355
```
324356

325357
## Dynamic API Backend
358+
326359
Please notice that, `API_URL` is saved into bundle on build, CANNOT be changed
327360
on runtime! You may use [proxy](../proxy) module for dynamically route api requests to different backend on test/staging/production.
328361

@@ -341,13 +374,15 @@ on runtime! You may use [proxy](../proxy) module for dynamically route api reque
341374
```
342375

343376
Start Nuxt
377+
344378
```
345379
[AXIOS] Base URL: http://localhost:3000/api | Browser: /api
346380
[HPM] Proxy created: /api -> http://www.mocky.io
347381
[HPM] Proxy rewrite rule created: "^/api" ~> "/v2"
348382
```
349383

350384
Now you can make requests to backend: (Works fine in both SSR and Browser)
385+
351386
```js
352387
async asyncData({ app }) {
353388
// Magically makes request to http://www.mocky.io/v2/59388bb4120000dc00a672e2
@@ -360,13 +395,15 @@ async asyncData({ app }) {
360395
```
361396

362397
Details
363-
- `'@nuxtjs/axios'`
364-
- By default axios plugin sets base url to `http://[host]:[port]/api` which is `http://localhost:3000/api`
365398

366-
- `'/api': 'http://www.mocky.io/v2'`
367-
- This line creates a server middleware to pass requests from `/api` to `http://www.mocky.io/v2`
368-
- We used `pathRewrite` to remove `/api` from starting of requests and change it to `/v2`
369-
- For more information and advanced usage please refer to [proxy](https://github.com/nuxt-community/modules/blob/master/packages/proxy) docs.
399+
* `'@nuxtjs/axios'`
400+
401+
* By default axios plugin sets base url to `http://[host]:[port]/api` which is `http://localhost:3000/api`
402+
403+
* `'/api': 'http://www.mocky.io/v2'`
404+
* This line creates a server middleware to pass requests from `/api` to `http://www.mocky.io/v2`
405+
* We used `pathRewrite` to remove `/api` from starting of requests and change it to `/v2`
406+
* For more information and advanced usage please refer to [proxy](https://github.com/nuxt-community/modules/blob/master/packages/proxy) docs.
370407

371408
## License
372409

0 commit comments

Comments
 (0)