Skip to content

Commit

Permalink
feat: allow adding custom headers with nuxt config (#294)
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardogobbosouza authored and pi0 committed Oct 23, 2019
1 parent fba95fa commit af1e86d
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 23 deletions.
23 changes: 22 additions & 1 deletion docs/options.md
Expand Up @@ -43,7 +43,7 @@ Environment variable `API_URL` can be used to **override** `baseURL`.


### `browserBaseURL` ### `browserBaseURL`


* Default: `baseURL` * Default: `baseURL`
**WARNING:** when the `proxy` option is enabled the default for browserBaseURL becomes `prefix` instead of `baseURL` **WARNING:** when the `proxy` option is enabled the default for browserBaseURL becomes `prefix` instead of `baseURL`


Defines the base URL which is used and prepended to make client side requests. Defines the base URL which is used and prepended to make client side requests.
Expand Down Expand Up @@ -148,3 +148,24 @@ This also helps making consistent requests in both SSR and Client Side code.
* Default `['host', 'accept', 'cf-ray', 'cf-connecting-ip', 'content-length']` * Default `['host', 'accept', 'cf-ray', 'cf-connecting-ip', 'content-length']`


This is useful and efficient only when `proxyHeaders` is set to true. Removes unwanted requests headers to the API backend in SSR. This is useful and efficient only when `proxyHeaders` is set to true. Removes unwanted requests headers to the API backend in SSR.

### `headers`

Headers added to all requests. If provided, will be merged with the defaults.

```js
{
common: {
'Accept': 'application/json, text/plain, */*'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
}
```

- **NOTE:** Do NOT include any credentials or tokens here. One can easily access them.
- **NOTE:** This headers are effective to ALL requests. Please take care and consider providing special headers on each call that needs this unless you are pretty sure you always need to add headers.
22 changes: 18 additions & 4 deletions lib/module.js
@@ -1,5 +1,6 @@
const path = require('path') const path = require('path')
const consola = require('consola') const consola = require('consola')
const defu = require('defu')


const logger = consola.withScope('nuxt:axios') const logger = consola.withScope('nuxt:axios')


Expand Down Expand Up @@ -36,8 +37,21 @@ function axiosModule(_moduleOptions) {
// HTTPS // HTTPS
const https = Boolean(this.options.server && this.options.server.https) const https = Boolean(this.options.server && this.options.server.https)


// Headers
const headers = {
common: {
'Accept': 'application/json, text/plain, */*'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
}

// Apply defaults // Apply defaults
const options = { const options = defu(moduleOptions, {
baseURL: `http://${defaultHost}:${defaultPort}${prefix}`, baseURL: `http://${defaultHost}:${defaultPort}${prefix}`,
browserBaseURL: null, browserBaseURL: null,
credentials: false, credentials: false,
Expand All @@ -48,8 +62,8 @@ function axiosModule(_moduleOptions) {
proxy: false, proxy: false,
retry: false, retry: false,
https, https,
...moduleOptions headers
} })


// ENV overrides // ENV overrides


Expand All @@ -75,7 +89,7 @@ function axiosModule(_moduleOptions) {


// Convert http:// to https:// if https option is on // Convert http:// to https:// if https option is on
if (options.https === true) { if (options.https === true) {
const https = s => s.indexOf('//localhost:') > -1 ? s : s.replace('http://', 'https://') const https = s => s.includes('//localhost:') ? s : s.replace('http://', 'https://')
options.baseURL = https(options.baseURL) options.baseURL = https(options.baseURL)
options.browserBaseURL = https(options.browserBaseURL) options.browserBaseURL = https(options.browserBaseURL)
} }
Expand Down
12 changes: 1 addition & 11 deletions lib/plugin.js
Expand Up @@ -156,17 +156,7 @@ export default (ctx, inject) => {
// Create fresh objects for all default header scopes // Create fresh objects for all default header scopes
// Axios creates only one which is shared across SSR requests! // Axios creates only one which is shared across SSR requests!
// https://github.com/mzabriskie/axios/blob/master/lib/defaults.js // https://github.com/mzabriskie/axios/blob/master/lib/defaults.js
const headers = { const headers = <%= JSON.stringify(options.headers, null, 4) %>
common : {
'Accept': 'application/json, text/plain, */*'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
}


const axiosOptions = { const axiosOptions = {
baseURL, baseURL,
Expand Down
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -26,7 +26,8 @@
"@nuxtjs/proxy": "^1.3.3", "@nuxtjs/proxy": "^1.3.3",
"axios": "^0.19.0", "axios": "^0.19.0",
"axios-retry": "^3.1.2", "axios-retry": "^3.1.2",
"consola": "^2.10.1" "consola": "^2.10.1",
"defu": "^0.0.3"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "latest", "@babel/core": "latest",
Expand Down
2 changes: 1 addition & 1 deletion test/fixture/pages/asyncData.vue
Expand Up @@ -6,7 +6,7 @@


<script> <script>
export default { export default {
async asyncData({ app }) { async asyncData ({ app }) {
const res = await app.$axios.$get('foo/bar') const res = await app.$axios.$get('foo/bar')
return { return {
res res
Expand Down
4 changes: 2 additions & 2 deletions test/fixture/pages/mounted.vue
Expand Up @@ -6,13 +6,13 @@


<script> <script>
export default { export default {
data() { data () {
return { return {
res: '' res: ''
} }
}, },
async mounted() { async mounted () {
// Request with full url becasue we are in JSDom env // Request with full url becasue we are in JSDom env
this.res = await this.$axios.$get('http://localhost:3000/test_api/foo/bar') this.res = await this.$axios.$get('http://localhost:3000/test_api/foo/bar')
} }
Expand Down
6 changes: 3 additions & 3 deletions test/fixture/pages/ssr.vue
Expand Up @@ -11,15 +11,15 @@ let reqCtr = 1
export default { export default {
computed: { computed: {
axiosSessionId() { axiosSessionId () {
return this.$axios.defaults.headers.common.SessionId return this.$axios.defaults.headers.common.SessionId
}, },
axiosEncoding() { axiosEncoding () {
return this.$axios.defaults.headers.common['accept-encoding'] return this.$axios.defaults.headers.common['accept-encoding']
} }
}, },
fetch({ app, route }) { fetch ({ app, route }) {
const doLogin = route.query.login !== undefined const doLogin = route.query.login !== undefined
if (doLogin) { if (doLogin) {
app.$axios.setHeader('SessionId', reqCtr++) app.$axios.setHeader('SessionId', reqCtr++)
Expand Down

0 comments on commit af1e86d

Please sign in to comment.