Skip to content

Commit

Permalink
fix: preserve default headers with custom headers (#452)
Browse files Browse the repository at this point in the history
Co-authored-by: Gábor Egyed <gabor.egyed@gmail.com>
  • Loading branch information
pi0 and 1ed committed Dec 14, 2020
1 parent 76e0d50 commit 55f994f
Show file tree
Hide file tree
Showing 11 changed files with 97 additions and 51 deletions.
9 changes: 7 additions & 2 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,16 @@ const createAxiosInstance = axiosOptions => {
// Extend axios proto
extendAxiosInstance(axios)

// Intercept to apply default headers
axios.onRequest((config) => {
config.headers = { ...axios.defaults.headers.common, ...config.headers }
})

// Setup interceptors
<% if (options.debug) { %>setupDebugInterceptor(axios) <% } %>
<% if (options.credentials) { %>setupCredentialsInterceptor(axios)<% } %>
<% if (options.credentials) { %>setupCredentialsInterceptor(axios) <% } %>
<% if (options.progress) { %>setupProgress(axios) <% } %>
<% if (options.retry) { %>axiosRetry(axios, <%= serialize(options.retry) %>)<% } %>
<% if (options.retry) { %>axiosRetry(axios, <%= serialize(options.retry) %>) <% } %>

return axios
}
Expand Down
10 changes: 5 additions & 5 deletions test/axios.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ const testSuite = () => {
const call = addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
const options = call[0].options
const proto = options.https ? 'https' : 'http'
expect(options.baseURL.toString()).toBe(`${proto}://localhost:3000/test_api`)
expect(options.browserBaseURL.toString()).toBe('/test_api')
expect(options.baseURL.toString()).toBe(`${proto}://localhost:3000/api`)
expect(options.browserBaseURL.toString()).toBe('/api')
})

test('asyncData', async () => {
Expand Down Expand Up @@ -121,7 +121,7 @@ describe('module', () => {
describe('other options', () => {
beforeAll(async () => {
config.axios = {
prefix: '/test_api',
prefix: '/api',
proxy: {},
credentials: true,
https: true,
Expand All @@ -141,7 +141,7 @@ describe('other options', () => {
describe('browserBaseURL', () => {
beforeAll(async () => {
config.axios = {
browserBaseURL: '/test_api'
browserBaseURL: '/api'
}

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

Expand Down
20 changes: 0 additions & 20 deletions test/fixture/api.js

This file was deleted.

4 changes: 4 additions & 0 deletions test/fixture/api/cookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default (req, res) => {
const reqCookie = (new URLSearchParams(req.headers.cookie || '').get('mycookie') || '').split(';')[0].trim()
res.end(reqCookie || '')
}
17 changes: 17 additions & 0 deletions test/fixture/api/echo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export default async (req, res) => {
const query = new URL(req.url, 'http://localhost:3000').query
if (query && query.delay) {
await sleep(query.delay)
}

res.end(JSON.stringify({
url: req.url,
method: req.method
}))
}

function sleep (ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
7 changes: 5 additions & 2 deletions test/fixture/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ module.exports = {
modules: [
{ handler: require('../../') }
],
serverMiddleware: ['~/api.js'],
serverMiddleware: {
'/api/echo': '~/api/echo',
'/api/cookie': '~/api/cookie'
},
axios: {
prefix: '/test_api',
prefix: '/api',
proxy: true,
credentials: true,
debug: true,
Expand Down
2 changes: 1 addition & 1 deletion test/fixture/pages/asyncData.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<script>
export default {
async asyncData ({ app }) {
const res = await app.$axios.$get('foo/bar')
const res = await app.$axios.$get('echo/foo/bar')
return {
res
}
Expand Down
28 changes: 15 additions & 13 deletions test/fixture/pages/cancelToken.vue
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
<template>
<div>
there should be no loading bar left over:
<button @click="test">Fake Request</button>
<button @click="test">
Fake Request
</button>
</div>
</template>

<script>
export default {
methods: {
test() {
const source = this.$axios.CancelToken.source();
test () {
const source = this.$axios.CancelToken.source()
this.$axios
.$post(
"http://localhost:3000/test_api/foo/bar?delay=1000",
{ data: "test" },
'http://localhost:3000/api/echo/foo/bar?delay=1000',
{ data: 'test' },
{
cancelToken: source.token,
cancelToken: source.token
}
)
.catch((err) => {
if (this.$axios.isCancel(err)) {
console.log("request canceled");
console.log('request canceled')
}
});
})
setTimeout(function () {
source.cancel();
}, 500);
},
},
};
source.cancel()
}, 500)
}
}
}
</script>
35 changes: 35 additions & 0 deletions test/fixture/pages/cookie.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<template>
<div>
<pre style="display: none">_req:{{ reqCookie }}</pre>
<p>Pass: {{ pass }}</p>
</div>
</template>

<script>
export default {
async asyncData ({ app }) {
const reqCookie = (await app.$axios.$get('/cookie', {
headers: { Accept: 'application/json' }
})) + ''
return {
reqCookie
}
},
data () {
return {
pass: '?'
}
},
async mounted () {
const randomValue = Math.round(Math.random() * 1000) + ''
document.cookie = `mycookie=${randomValue}; path=/`
// Render page with server-side, expecting to be rendered with same new cookie
const html = await this.$axios.$get(window.location.href)
const m = html.match(/_req:(\w+)/)
const profifiedSSRCookie = m && m[1]
this.pass = randomValue === profifiedSSRCookie
}
}
</script>
2 changes: 1 addition & 1 deletion test/fixture/pages/mounted.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default {
async mounted () {
// 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/api/echo/foo/bar')
}
}
</script>
14 changes: 7 additions & 7 deletions test/fixture/pages/ssr.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
let reqCtr = 1
export default {
fetch ({ app, route }) {
const doLogin = route.query.login !== undefined
if (doLogin) {
app.$axios.setHeader('SessionId', reqCtr++)
}
},
computed: {
axiosSessionId () {
return this.$axios.defaults.headers.common.SessionId
Expand All @@ -23,7 +29,7 @@ export default {
return this.newInstance.defaults.headers.common.SessionId
},
newInstanceHeaders () {
return this.newInstance.defaults.headers
return this.newInstance.defaults.headers.common
}
},
created () {
Expand All @@ -32,12 +38,6 @@ export default {
'X-Requested-With': 'XMLHttpRequest'
}
})
},
fetch ({ app, route }) {
const doLogin = route.query.login !== undefined
if (doLogin) {
app.$axios.setHeader('SessionId', reqCtr++)
}
}
}
</script>

0 comments on commit 55f994f

Please sign in to comment.