Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the response headers with Nuxt 3's useFetch?

Tags:

nuxt3.js

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 } 🤔

like image 732
Tim Avatar asked Oct 16 '25 16:10

Tim


1 Answers

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>
like image 108
Reagan Avatar answered Oct 18 '25 17:10

Reagan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!