Permalink
Browse files

feat(axios): AXIOS_CREDENTIALS, AXIOS_SSR_HEADERS

  • Loading branch information...
pi0 committed Jun 9, 2017
1 parent e51d0ad commit 4dfdc2d9719ee502e8479c844de96425daf4cc58
Showing with 15 additions and 3 deletions.
  1. +4 −0 modules/axios/README.md
  2. +7 −0 modules/axios/index.js
  3. +4 −3 modules/axios/plugin.js
@@ -6,6 +6,7 @@
- Exposes `setToken` function to `$axios` so we can easily and globally set authentication tokens.
- Throws *nuxt-friendly* exceptions.
- Automatically enables `withCredentials` when requesting to base URL.
- Automatically set request headers in SSR

## Setup
- Add `@nuxtjs/axios` dependency using yarn or npm to your project
@@ -91,6 +92,9 @@ Environment variable | Default | Description
---------------------|-----------------------------------|--------------------------------------------
API_URL | `http://[localhost]:[3000]/api` | Base url for requests in server-side (SSR)
API_URL_BROWSER | `/api` (relative API_URL) | Base url for requests in client-side
AXIOS_CREDENTIALS | `true` | Send credentials only to relative and API Backend requests
AXIOS_SSR_HEADERS | `true` | Use client request headers in SSR as axios default headers (useful for cookie based auth)
## Dynamic API Backend
Please notice that, `API_URL` is saved into bundle on build, CANNOT be changed
@@ -24,6 +24,13 @@ module.exports = function nuxtAxios (options) {
setOpt('API_URL', API_URL)
setOpt('API_URL_BROWSER', API_URL_BROWSER)

// Other options
const ensureOpt = (key, default_val) => {
setOpt(key, getOpt(key, default_val))
}
ensureOpt('AXIOS_CREDENTIALS', true)
ensureOpt('AXIOS_SSR_HEADERS', true)

// Register plugin
this.addPlugin({
src: path.resolve(__dirname, 'plugin.js'),
@@ -68,9 +68,10 @@ export default (ctx) => {
: (process.env.API_URL || '<%= options.API_URL %>')

const axios = Axios.create({
baseURL
baseURL,
<% if(options.AXIOS_SSR_HEADERS) { %>headers: (req && request.headers) ? request.headers : {} <% } %>
})

<% if(options.AXIOS_CREDENTIALS) { %>
// Send credentials only to relative and API Backend requests
axios.interceptors.request.use(config => {
if (config.withCredentials === undefined) {
@@ -80,7 +81,7 @@ export default (ctx) => {
}
return config
});

<% } %>
// Error handler
axios.interceptors.response.use(undefined, (error) => {
if (error.response && error.response.status === 401) {

0 comments on commit 4dfdc2d

Please sign in to comment.