Skip to content

Commit 55f994f

Browse files
pi01ed
andauthored
fix: preserve default headers with custom headers (#452)
Co-authored-by: Gábor Egyed <[email protected]>
1 parent 76e0d50 commit 55f994f

File tree

11 files changed

+97
-51
lines changed

11 files changed

+97
-51
lines changed

lib/plugin.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,16 @@ const createAxiosInstance = axiosOptions => {
6161
// Extend axios proto
6262
extendAxiosInstance(axios)
6363

64+
// Intercept to apply default headers
65+
axios.onRequest((config) => {
66+
config.headers = { ...axios.defaults.headers.common, ...config.headers }
67+
})
68+
6469
// Setup interceptors
6570
<% if (options.debug) { %>setupDebugInterceptor(axios) <% } %>
66-
<% if (options.credentials) { %>setupCredentialsInterceptor(axios)<% } %>
71+
<% if (options.credentials) { %>setupCredentialsInterceptor(axios) <% } %>
6772
<% if (options.progress) { %>setupProgress(axios) <% } %>
68-
<% if (options.retry) { %>axiosRetry(axios, <%= serialize(options.retry) %>)<% } %>
73+
<% if (options.retry) { %>axiosRetry(axios, <%= serialize(options.retry) %>) <% } %>
6974

7075
return axios
7176
}

test/axios.test.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ const testSuite = () => {
3232
const call = addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
3333
const options = call[0].options
3434
const proto = options.https ? 'https' : 'http'
35-
expect(options.baseURL.toString()).toBe(`${proto}://localhost:3000/test_api`)
36-
expect(options.browserBaseURL.toString()).toBe('/test_api')
35+
expect(options.baseURL.toString()).toBe(`${proto}://localhost:3000/api`)
36+
expect(options.browserBaseURL.toString()).toBe('/api')
3737
})
3838

3939
test('asyncData', async () => {
@@ -121,7 +121,7 @@ describe('module', () => {
121121
describe('other options', () => {
122122
beforeAll(async () => {
123123
config.axios = {
124-
prefix: '/test_api',
124+
prefix: '/api',
125125
proxy: {},
126126
credentials: true,
127127
https: true,
@@ -141,7 +141,7 @@ describe('other options', () => {
141141
describe('browserBaseURL', () => {
142142
beforeAll(async () => {
143143
config.axios = {
144-
browserBaseURL: '/test_api'
144+
browserBaseURL: '/api'
145145
}
146146

147147
await setupNuxt(config)
@@ -156,7 +156,7 @@ describe('browserBaseURL', () => {
156156
const call = addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
157157
const options = call[0].options
158158
expect(options.baseURL.toString()).toBe('http://localhost:3000/')
159-
expect(options.browserBaseURL.toString()).toBe('/test_api')
159+
expect(options.browserBaseURL.toString()).toBe('/api')
160160
})
161161
})
162162

test/fixture/api.js

Lines changed: 0 additions & 20 deletions
This file was deleted.

test/fixture/api/cookie.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export default (req, res) => {
2+
const reqCookie = (new URLSearchParams(req.headers.cookie || '').get('mycookie') || '').split(';')[0].trim()
3+
res.end(reqCookie || '')
4+
}

test/fixture/api/echo.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
export default async (req, res) => {
2+
const query = new URL(req.url, 'http://localhost:3000').query
3+
if (query && query.delay) {
4+
await sleep(query.delay)
5+
}
6+
7+
res.end(JSON.stringify({
8+
url: req.url,
9+
method: req.method
10+
}))
11+
}
12+
13+
function sleep (ms) {
14+
return new Promise((resolve) => {
15+
setTimeout(resolve, ms)
16+
})
17+
}

test/fixture/nuxt.config.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,12 @@ module.exports = {
1010
modules: [
1111
{ handler: require('../../') }
1212
],
13-
serverMiddleware: ['~/api.js'],
13+
serverMiddleware: {
14+
'/api/echo': '~/api/echo',
15+
'/api/cookie': '~/api/cookie'
16+
},
1417
axios: {
15-
prefix: '/test_api',
18+
prefix: '/api',
1619
proxy: true,
1720
credentials: true,
1821
debug: true,

test/fixture/pages/asyncData.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<script>
88
export default {
99
async asyncData ({ app }) {
10-
const res = await app.$axios.$get('foo/bar')
10+
const res = await app.$axios.$get('echo/foo/bar')
1111
return {
1212
res
1313
}

test/fixture/pages/cancelToken.vue

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,35 @@
11
<template>
22
<div>
33
there should be no loading bar left over:
4-
<button @click="test">Fake Request</button>
4+
<button @click="test">
5+
Fake Request
6+
</button>
57
</div>
68
</template>
79

810
<script>
911
export default {
1012
methods: {
11-
test() {
12-
const source = this.$axios.CancelToken.source();
13+
test () {
14+
const source = this.$axios.CancelToken.source()
1315
this.$axios
1416
.$post(
15-
"http://localhost:3000/test_api/foo/bar?delay=1000",
16-
{ data: "test" },
17+
'http://localhost:3000/api/echo/foo/bar?delay=1000',
18+
{ data: 'test' },
1719
{
18-
cancelToken: source.token,
20+
cancelToken: source.token
1921
}
2022
)
2123
.catch((err) => {
2224
if (this.$axios.isCancel(err)) {
23-
console.log("request canceled");
25+
console.log('request canceled')
2426
}
25-
});
27+
})
2628
2729
setTimeout(function () {
28-
source.cancel();
29-
}, 500);
30-
},
31-
},
32-
};
30+
source.cancel()
31+
}, 500)
32+
}
33+
}
34+
}
3335
</script>

test/fixture/pages/cookie.vue

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<template>
2+
<div>
3+
<pre style="display: none">_req:{{ reqCookie }}</pre>
4+
<p>Pass: {{ pass }}</p>
5+
</div>
6+
</template>
7+
8+
<script>
9+
export default {
10+
async asyncData ({ app }) {
11+
const reqCookie = (await app.$axios.$get('/cookie', {
12+
headers: { Accept: 'application/json' }
13+
})) + ''
14+
return {
15+
reqCookie
16+
}
17+
},
18+
data () {
19+
return {
20+
pass: '?'
21+
}
22+
},
23+
async mounted () {
24+
const randomValue = Math.round(Math.random() * 1000) + ''
25+
document.cookie = `mycookie=${randomValue}; path=/`
26+
27+
// Render page with server-side, expecting to be rendered with same new cookie
28+
const html = await this.$axios.$get(window.location.href)
29+
const m = html.match(/_req:(\w+)/)
30+
const profifiedSSRCookie = m && m[1]
31+
32+
this.pass = randomValue === profifiedSSRCookie
33+
}
34+
}
35+
</script>

test/fixture/pages/mounted.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export default {
1414
1515
async mounted () {
1616
// Request with full url becasue we are in JSDom env
17-
this.res = await this.$axios.$get('http://localhost:3000/test_api/foo/bar')
17+
this.res = await this.$axios.$get('http://localhost:3000/api/echo/foo/bar')
1818
}
1919
}
2020
</script>

test/fixture/pages/ssr.vue

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@
1212
let reqCtr = 1
1313
1414
export default {
15+
fetch ({ app, route }) {
16+
const doLogin = route.query.login !== undefined
17+
if (doLogin) {
18+
app.$axios.setHeader('SessionId', reqCtr++)
19+
}
20+
},
1521
computed: {
1622
axiosSessionId () {
1723
return this.$axios.defaults.headers.common.SessionId
@@ -23,7 +29,7 @@ export default {
2329
return this.newInstance.defaults.headers.common.SessionId
2430
},
2531
newInstanceHeaders () {
26-
return this.newInstance.defaults.headers
32+
return this.newInstance.defaults.headers.common
2733
}
2834
},
2935
created () {
@@ -32,12 +38,6 @@ export default {
3238
'X-Requested-With': 'XMLHttpRequest'
3339
}
3440
})
35-
},
36-
fetch ({ app, route }) {
37-
const doLogin = route.query.login !== undefined
38-
if (doLogin) {
39-
app.$axios.setHeader('SessionId', reqCtr++)
40-
}
4141
}
4242
}
4343
</script>

0 commit comments

Comments
 (0)