How can I check response status code when using NuxtJs useFetch
?
Currently I'm handling response as follows, but I cannot find anywhere how to get the exact response status code, only an error message e.g. FetchError: 403 Forbidden
.
useFetch(url, options).then(
(res) => {
const data = res.data.value;
const error = res.error.value;
if (error) {
console.error(error);
// handle error
} else {
console.log(data);
// handle success
}
},
(error) => {
console.error(error);
}
);
in your template you can, use error.statusCode
but in your script you, can use error.value.statusCode
check this :
<template>
<div>
error : {{ error.statusCode }}
</div>
</template>
<script setup>
const { data, pending, error, refresh } = await useFetch("https://api.nuxtjs.dev/mountais",
{ pick: ["title"] }
);
console.log(error.value.statusCode);
</script>
The error
object will be empty if you get your request successfully
The following way is better if you want to do something in the script part (set sepcific message etc)
await useFetch(URL, {
onResponse({request, response, options}) {
// Process the response data
if (response.status === 200) {
//your code
}
},
onResponseError({request, response, options}) {
if (response.status === 400) {
//your code
} else {
//your code
}
router.push("/")
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With