У Вас нет аккаунта?
13 |
Забыли пароль?
17 |
Вспомнили пароль?
14 |
Не помните старый пароль?
14 |
Готовый шаблон с регистрацией, подтверждением почты и авторизацией.
12 |23 | “First, solve the problem. Then, write the code.” 24 | 29 |30 |
8 | Теперь Вы можете
9 |
Проверьте, что текущая ссылка соответствует ссылке в письме.
16 |Ошибка: Неверные данные.
17 | 18 |Вы уже зарегистрированы?
14 |
2 |
3 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
Secure and Easy Axios integration with Nuxt.js.
30 | 31 | [📖 Release Notes](./CHANGELOG.md) 32 | 33 | # Table of Contents 34 | 35 | - [Features](#features) 36 | - [Setup](#setup) 37 | - [Usage](#usage) 38 | - [Component](#component-asyncdata) 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 | - [redirectError](#redirecterror) 47 | - [requestInterceptor](#requestinterceptor) 48 | - [responseInterceptor](#responseinterceptor) 49 | - [init](#init) 50 | - [errorHandler](#errorhandler) 51 | - [Helpers](#helpers) 52 | - [Fetch Style Requests](#fetch-style-requests) 53 | - [Set Header](#setheadername-value-scopescommon) 54 | - [Set Token](#settokentoken-type-scopescommon) 55 | - [Dynamic API Backend](#dynamic-api-backend) 56 | 57 | ## Features 58 | 59 | - Automatically set base URL for client & server side 60 | - Exposes `setToken` function to `$axios` so we can easily and globally set authentication tokens 61 | - Throws *nuxt-friendly* errors and optionally redirect on specific error codes 62 | - Automatically enables `withCredentials` when requesting to base URL](#credentials) 63 | - Proxy request headers in SSR (Useful for auth) 64 | - Fetch Style requests 65 | 66 | ## Setup 67 | 68 | Install with npm: 69 | ```bash 70 | >_ npm install @nuxtjs/axios 71 | ``` 72 | 73 | Install with yarn: 74 | ```bash 75 | >_ yarn add @nuxtjs/axios 76 | ``` 77 | 78 | **nuxt.config.js** 79 | 80 | ```js 81 | { 82 | modules: [ 83 | '@nuxtjs/axios', 84 | ], 85 | 86 | axios: { 87 | // proxyHeaders: false 88 | } 89 | } 90 | ``` 91 | 92 | ## Usage 93 | 94 | ### Component `asyncData` 95 | 96 | ```js 97 | async asyncData({ app }) { 98 | const ip = await app.$axios.$get('http://icanhazip.com') 99 | return { ip } 100 | } 101 | ``` 102 | 103 | ### Store `nuxtServerInit` 104 | ```js 105 | async nuxtServerInit ({ commit }, { app }) { 106 | const ip = await app.$axios.$get('http://icanhazip.com') 107 | commit('SET_IP', ip) 108 | } 109 | ``` 110 | 111 | ### Store actions 112 | (Needs Nuxt >= 1.0.0-RC8) 113 | 114 | ```js 115 | // In store 116 | { 117 | actions: { 118 | async getIP ({ commit }) { 119 | const ip = await this.$axios.$get('http://icanhazip.com') 120 | commit('SET_IP', ip) 121 | } 122 | } 123 | } 124 | ``` 125 | 126 | ## Options 127 | You can pass options using module options or `axios` section in `nuxt.config.js` 128 | 129 | ### `baseURL` 130 | - Default: `http://[HOST]:[PORT]/api` 131 | 132 | Base URL is required for requests in server-side & SSR and prepended to all requests with relative path. 133 | You can also use environment variable `API_URL` which **overrides** `baseURL`. 134 | 135 | ### `browserBaseURL` 136 | - Default: `/api` 137 | 138 | Base URL which is used in client side prepended to all requests with relative path. 139 | You can also use environment variable `API_URL_BROWSER` which **overrides** `browserBaseURL`. 140 | 141 | - If `browserBaseURL` is not provided it defaults to `baseURL` value. 142 | - If hostname & port of `browserbaseURL` are equal to nuxt server, it defaults to relative part of `baseURL`. 143 | So if your nuxt application is being accessed under a different domain, requests go to same origin and prevents Cross-Origin problems. 144 | 145 | ### `credentials` 146 | - Default: `true` 147 | 148 | Adds an interceptor to automatically set `withCredentials` config of axios when requesting to `baseUrl` 149 | which allows passing authentication headers to backend. 150 | 151 | ### `debug` 152 | - Default: `false` 153 | 154 | Adds interceptors to log all responses and requests 155 | 156 | ### `proxyHeaders` 157 | - Default: `true` 158 | 159 | In SSR context, sets client request header as axios default request headers. 160 | This is useful for making requests which need cookie based auth on server side. 161 | Also helps making consistent requests in both SSR and Client Side code. 162 | 163 | > **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. 164 | 165 | ### `redirectError` 166 | - Default: `{}` 167 | 168 | This option is a map from specific error codes to page which they should be redirect. 169 | For example if you want redirecting all `401` errors to `/login` use: 170 | ```js 171 | axios: { 172 | redirectError: { 173 | 401: '/login' 174 | } 175 | } 176 | ``` 177 | 178 | ### `requestInterceptor` 179 | - Default: `null` 180 | 181 | Function for manipulating axios requests. Useful for setting custom headers, 182 | for example based on the store state. The second argument is the nuxt context. 183 | 184 | ```js 185 | requestInterceptor: (config, { store }) => { 186 | if (store.state.token) { 187 | config.headers.common['Authorization'] = store.state.token 188 | } 189 | return config 190 | } 191 | ``` 192 | 193 | ### `responseInterceptor` 194 | - Default: `null` 195 | 196 | ```js 197 | responseInterceptor: (response, ctx) => { 198 | return response 199 | } 200 | ``` 201 | 202 | 203 | Function for manipulating axios responses. 204 | 205 | ### `init` 206 | - Default: `null` 207 | 208 | Function `init(axios, ctx)` to do additional things with axios. Example: 209 | 210 | ```js 211 | axios: { 212 | init(axios, ctx) { 213 | axios.defaults.xsrfHeaderName = 'X-CSRF-TOKEN' 214 | } 215 | } 216 | ``` 217 | 218 | ### `errorHandler` 219 | - Default: (Return promise rejection with error) 220 | 221 | Function for custom global error handler. 222 | This example uses nuxt default error page. 223 | 224 | ```js 225 | axios: { 226 | errorHandler (error, { error }) { 227 | error('Request Error: ' + error) 228 | } 229 | }, 230 | ``` 231 | 232 | ## Helpers 233 | 234 | ### Fetch Style requests 235 | Axios plugin also supports fetch style requests with `$` prefixed methods: 236 | ```js 237 | // Normal usage with axios 238 | let data = (await $axios.get('...')).data 239 | 240 | // Fetch Style 241 | let data = await $axios.$get('...') 242 | ``` 243 | 244 | ### `setHeader(name, value, scopes='common')` 245 | Axios instance has a helper to easily set any header. 246 | 247 | Parameters: 248 | - **name**: Name of the header 249 | - **value**: Value of the header 250 | - **scopes**: Send only on specific type of requests. Defaults 251 | - Type: *Array* or *String* 252 | - Defaults to `common` meaning all types of requests 253 | - Can be `get`, `post`, `delete`, ... 254 | 255 | ```js 256 | // Adds header: `Authorization: 123` to all requests 257 | this.$axios.setHeader('Authorization', '123') 258 | 259 | // Overrides `Authorization` header with new value 260 | this.$axios.setHeader('Authorization', '456') 261 | 262 | // Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests 263 | this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', ['post']) 264 | 265 | // Removes default Content-Type header from `post` scope 266 | this.$axios.setHeader('Content-Type', false, ['post']) 267 | ``` 268 | 269 | ### `setToken(token, type, scopes='common')` 270 | Axios instance has an additional helper to easily set global authentication header. 271 | 272 | Parameters: 273 | - **token**: Authorization token 274 | - **type**: Authorization token prefix(Usually `Bearer`). 275 | - **scopes**: Send only on specific type of requests. Defaults 276 | - Type: *Array* or *String* 277 | - Defaults to `common` meaning all types of requests 278 | - Can be `get`, `post`, `delete`, ... 279 | 280 | ```js 281 | // Adds header: `Authorization: 123` to all requests 282 | this.$axios.setToken('123') 283 | 284 | // Overrides `Authorization` header with new value 285 | this.$axios.setToken('456') 286 | 287 | // Adds header: `Authorization: Bearer 123` to all requests 288 | this.$axios.setToken('123', 'Bearer') 289 | 290 | // Adds header: `Authorization: Bearer 123` to only post and delete requests 291 | this.$axios.setToken('123', 'Bearer', ['post', 'delete']) 292 | 293 | // Removes default Authorization header from `common` scope (all requests) 294 | this.$axios.setToken(false) 295 | ``` 296 | 297 | ## Dynamic API Backend 298 | Please notice that, `API_URL` is saved into bundle on build, CANNOT be changed 299 | on runtime! You may use [proxy](../proxy) module for dynamically route api requests to different backend on test/staging/production. 300 | 301 | **Example: (`nuxt.config.js`)** 302 | 303 | ```js 304 | { 305 | modules: [ 306 | '@nuxtjs/axios', 307 | '@nuxtjs/proxy' 308 | ], 309 | proxy: [ 310 | ['/api', { target: 'http://www.mocky.io', pathRewrite: { '^/api': '/v2' } }] 311 | ] 312 | } 313 | ``` 314 | 315 | Start Nuxt 316 | ``` 317 | [AXIOS] Base URL: http://localhost:3000/api | Browser: /api 318 | [HPM] Proxy created: /api -> http://www.mocky.io 319 | [HPM] Proxy rewrite rule created: "^/api" ~> "/v2" 320 | ``` 321 | 322 | Now you can make requests to backend: (Works fine in both SSR and Browser) 323 | ```js 324 | async asyncData({ app }) { 325 | // Magically makes request to http://www.mocky.io/v2/59388bb4120000dc00a672e2 326 | const nuxt = await app.$axios.$get('59388bb4120000dc00a672e2') 327 | 328 | return { 329 | nuxt // -> { nuxt: 'Works!' } 330 | } 331 | } 332 | ``` 333 | 334 | Details 335 | - `'@nuxtjs/axios'` 336 | - By default axios plugin sets base url to `http://[host]:[port]/api` which is `http://localhost:3000/api` 337 | 338 | - `'/api': 'http://www.mocky.io/v2'` 339 | - This line creates a server middleware to pass requests from `/api` to `http://www.mocky.io/v2` 340 | - We used `pathRewrite` to remove `/api` from starting of requests and change it to `/v2` 341 | - For more information and advanced usage please refer to [proxy](../proxy) docs. 342 | 343 | ## License 344 | 345 | [MIT License](./LICENSE) 346 | 347 | Copyright (c) 2017 Nuxt Community 348 | --------------------------------------------------------------------------------