feat: allow adding custom headers with nuxt config (#101)

* feat: allow adding custom headers with nuxt config

* fix: Ky headers are simple

* docs: `setToken` not accept custom headers

* style: indentation
master
Ricardo Gobbo de Souza 2020-05-26 14:38:55 -03:00 committed by GitHub
parent d25e71b65d
commit 2839260ea9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 42 additions and 22 deletions

View File

@ -145,3 +145,17 @@ When directing requests at a url protected by CloudFlare's CDN you should set th
* Default `['accept', 'host', 'cf-ray', 'cf-connecting-ip', 'content-length']`
Only efficient when `proxyHeaders` is set to true. Removes unwanted request headers to the API backend in SSR.
### `headers`
Headers added to all requests. If provided, will be merged with the defaults.
* Default: `{}`
:::tip Note
Do NOT include any credentials or tokens here. One can easily access them.
:::
:::tip 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.
:::

View File

@ -107,9 +107,6 @@ this.$http.setToken('456')
// Adds header: `Authorization: Bearer 123` to all requests
this.$http.setToken('123', 'Bearer')
// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$http.setToken('123', 'Bearer', ['post', 'delete'])
// Removes default Authorization header
this.$http.setToken(false)
```

View File

@ -45,6 +45,7 @@ function httpModule (_moduleOptions) {
serverTimeout: false,
clientTimeout: false,
https: false,
headers: {},
...moduleOptions
}

View File

@ -11,7 +11,6 @@ class HTTP {
this._ky = ky
}
setBaseURL (baseURL) {
this._defaults.prefixUrl = baseURL
}
@ -26,7 +25,7 @@ class HTTP {
setToken(token, type) {
const value = !token ? null : (type ? type + ' ' : '') + token
this.setHeader('authorization', value)
this.setHeader('Authorization', value)
}
_hook(name, fn) {
@ -85,7 +84,7 @@ for (let method of ['get', 'head', 'delete', 'post', 'put', 'patch']) {
} else if (_options.prefixUrl && typeof url === 'string' && url.startsWith('/')) {
// Prevents `ky` from throwing "`input` must not begin with a slash when using `prefixUrl`"
url = url.substr(1)
}
}
try {
const response = await this._ky[method](url, _options)
@ -111,19 +110,26 @@ export default (ctx, inject) => {
? '<%= options.browserBaseURL %>'
: (process.env._HTTP_BASE_URL_ || '<%= options.baseURL %>')
const headers = <%= JSON.stringify(options.headers, null, 2) %>
// Defaults
const defaults = {
retry: <%= options.retry %>,
timeout: process.server ? <%= options.serverTimeout %> : <%= options.clientTimeout %>,
prefixUrl,
headers: {}
headers
}
<% if (options.proxyHeaders) { %>
// Proxy SSR request headers headers
defaults.headers = (ctx.req && ctx.req.headers) ? { ...ctx.req.headers } : {}
<% for (let h of options.proxyHeadersIgnore) { %>delete defaults.headers['<%= h %>']
<% } %><% } %>
if (process.server && ctx.req && ctx.req.headers) {
const reqHeaders = { ...ctx.req.headers }
for (let h of <%= serialize(options.proxyHeadersIgnore) %>) {
delete reqHeaders[h]
}
defaults.headers = { ...reqHeaders, ...defaults.headers }
}
<% } %>
if (process.server) {
// Don't accept brotli encoding because Node can't parse it

View File

@ -1,13 +1,15 @@
<template>
<div>
<div>prefixUrl:{{ defaults.prefixUrl }}</div>
<div v-for="(value, key) in defaults.headers" :key="key">{{ key }}:{{ value }}</div>
<div v-for="(value, key) in defaults.headers" :key="key">
{{ key }}:{{ value }}
</div>
</div>
</template>
<script>
export default {
asyncData({ app: { $api } }) {
asyncData ({ app: { $api } }) {
return {
defaults: $api._defaults
}

View File

@ -10,20 +10,20 @@
let reqCtr = 1
export default {
computed: {
httpSessionId() {
return this.$http._defaults.headers.SessionId
},
httpEncoding() {
return this.$http._defaults.headers['accept-encoding']
}
},
fetch({ app, route }) {
fetch ({ app, route }) {
const doLogin = route.query.login !== undefined
if (doLogin) {
app.$http.setHeader('SessionId', reqCtr++)
}
},
computed: {
httpSessionId () {
return this.$http._defaults.headers.SessionId
},
httpEncoding () {
return this.$http._defaults.headers['accept-encoding']
}
}
}
</script>