最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin7PV0评论

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!

Post a comment

comment list (0)

  1. No comments so far