I am migrating a Nuxt2 that uses Axios to a Nuxt3 App that uses useFetch.
This following code accesse the response's header:
$axios.get(url, { responseType: 'arraybuffer' }).then((response) => {
const responseFilename = response?.headers?.['content-disposition']?.match(/filename="([\w\d_\-.]*)"/)?.[1];
const blob = new Blob([response.data], {
type: response.data.type ?? response.headers?.['content-type'],
});
How do I achieve this with useFetch ? All I get is { data, pending, error, refresh, status } 🤔
You can get the response headers using the onResponse
interceptor.
await useFetch('/api/', {
onResponse(context) {
// Output all available response headers
console.log(context.response.headers)
// Get the specific response header, e.g. authorization
console.log(context.response.headers.get('authorization'))
},
})
It will output the list of available headers in your terminal.
Tested and it works.
Edit: Get the header data from the interceptor
<script lang="ts" setup>
const authorizationHeader = ref<string | null>(null)
await useFetch('/api/test', {
onResponse (context) {
authorizationHeader.value = context.response.headers.get('authorization')
},
})
</script>
<template>
<div>
{{ authorizationHeader }}
</div>
</template>
<style scoped lang="css"></style>