Skip to content

Commit

Permalink
fix(axios): use relative API_URL if same host and port else API_URL
Browse files Browse the repository at this point in the history
  • Loading branch information
Pooya Parsa committed Jun 9, 2017
1 parent fe189e8 commit 3421d19
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
13 changes: 6 additions & 7 deletions modules/axios/README.md
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions modules/axios/index.js
Expand Up @@ -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'

Expand All @@ -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) => {
Expand Down

0 comments on commit 3421d19

Please sign in to comment.