最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vue.js - Issue with Nuxt’s useFetch returning null during SSR but working fine on the client - Stack Overflow

programmeradmin1浏览0评论

I am using Nuxt and have wrapped the useFetch function to handle API requests with a custom setup for headers, error handling, and other configurations. Below is my implementation:

// Core API wrapper
export const apiCore = (url, option) => {
    const runtimeConfig = useRuntimeConfig();
    let baseurl = runtimeConfig.public.baseURL;

    let res = useFetch(url, {
        baseURL: baseurl,
        onRequest({ options }) {
            options.headers = {
                timeout: 20000,
                ...option.headers,
            };
        },
        onResponse({ response }) {
            // Handle responses with status 200
        },
        onResponseError({ response }) {
            // Handle non-200 responses
        },
        ...option,
    });
    return res;
};

// GET request wrapper
export const GetApi = async (url, option) => {
    return new Promise((resolve, reject) => {
        apiCore(url, {
            method: 'GET',
            ...option,
        })
            .then((res) => resolve(res.data.value))
            .catch((err) => reject(err));
    });
};

When I use this wrapper to fetch data:

// Data fetching function
export const getData = async (start_time, end_time) => {
    start_time = start_time || new Date().getTime() - 86400000;
    end_time = end_time || new Date().getTime();

    try {
        let res = await GetApi('/api/data/1/10', { params: { start_time, end_time } });
        return res;
    } catch (err) {
        console.error(err);
        throw err;
    }
};

// Component usage
import { getData } from '~/api/getData.js';

const res = await getData();
console.log('res:', res);

The Issue: 1. During server-side rendering (SSR), the server retrieves a proxy object, but on the client, the value is null. 2. When rendering on the client side, the data is fetched successfully. 3. Using a faster API endpoint sometimes allows SSR to retrieve the correct data, but not consistently. 4. If I call the getData function inside the onMounted hook, the returned value is empty.

What I’ve Tried: • Checked API response times and confirmed slower responses exacerbate the issue. • Adjusted the useFetch options for headers and request parameters, but the behavior persists. • Attempted calling the API at different points in the component lifecycle, but the SSR-client discrepancy remains unresolved.

My Questions: • Is this issue related to Nuxt’s server-side rendering behavior or its handling of async operations during SSR? • Could this be a timeout issue, and how can I configure useFetch to handle it better? • How can I ensure useFetch returns consistent results during both SSR and client-side rendering?

Any insights or suggestions would be greatly appreciated. Thanks in advance!

发布评论

评论列表(0)

  1. 暂无评论