I have set up the nuxt 3 from the nuxt 3 official documents and used the only useFetch() composable to fetch data in app.vue file but it returns the error Error: fetch failed()
when we reload the page.
Please check my below code of app.vue file
<template>
{{data}}
</template>
<script setup>
const { data, pending, error, refresh } = useFetch('https://api.nuxtjs.dev/mountains',
{
method: "get",
});
console.log(data.value);
if (error.value) {
console.log(error.value);
}
</script>
I have tried useFetch and useLazyFetch composable to fetch the data but both returns the same error when we reload the page. I think there is some issue with client side or server side but don't know much about this. Also useFetch() returns result correctly when we visit that page again but it occurring error on initial api call or we hard reload the page.
HERE IS THE UPDATED ANSWER
I figured it out. we can fix this with the two cases that I mentioned below. I recommend case 2
CASE 1
We need to add ssr: false
in nuxt.config.js
. Maybe SSR is true by default if we need to use server-side rendering but if we want the single file application we need to keep ssr: false
. The above error is fixed with this.
nuxt.config.js
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
ssr: false,
})
if you keep ssr: false
then you will lose the many Nuxt ssr feature so you can go with case 2 without keeping ssr: true
CASE 2
There will be an issue with SSL certificate verification in localhost that's why this error occurred. to stop this add NODE_TLS_REJECT_UNAUTHORIZED=0
in your root .env
file. using this way, the error will be fixed and still you can use the SSR feature.