Permalink
Browse files

fix(axios): use relative `API_URL` if same host and port else `API_URL`

  • Loading branch information...
pi0 committed Jun 9, 2017
1 parent fe189e8 commit 3421d19a4f31b40aa8631be89c9701f4b5d878a8
Showing with 11 additions and 10 deletions.
  1. +6 −7 modules/axios/README.md
  2. +5 −3 modules/axios/index.js
@@ -88,13 +88,12 @@ export default {
## Config
Config can be done using environment variables (`proccess.env`), `options.env` or module options.
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)
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` if same host and port else `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
@@ -2,8 +2,6 @@ const chalk = require('chalk')
const path = require('path')
const { URL } = require('url')

const fixUrl = url => url.replace(/\/\//g, '/').replace(':/', '://')

const port = process.env.PORT || process.env.npm_package_config_nuxt_port || 3000
const host = process.env.HOST || process.env.npm_package_config_nuxt_host || 'localhost'

@@ -12,8 +10,12 @@ module.exports = function nuxtAxios (options) {
const getOpt = (key, default_val) => {
return process.env[key] || options[key] || options[key.toLowerCase()] || this.options.env[key] || default_val
}

const API_URL = getOpt('API_URL', `http://${host}:${port}/api`)
const API_URL_BROWSER = getOpt('API_URL_BROWSER', (new URL(API_URL)).pathname)
const url = new URL(API_URL)
const sameHost = url.host === `${host}:${port}`

const API_URL_BROWSER = getOpt('API_URL_BROWSER', sameHost ? url.pathname : API_URL)

// Commit new values to all sources
const setOpt = (key, val, env = true) => {

0 comments on commit 3421d19

Please sign in to comment.