【问题标题】:Can't return axios.all data from getServerSideProps无法从 getServerSideProps 返回 axios.all 数据
【发布时间】:2021-06-24 05:30:31
【问题描述】:

我想调用三个 URL 并从 getServerSideProps() 渲染它们的数据,所以我使用 axios.all([]) 是这样的:

export async function getServerSideProps(ctx) {
    const profileURL = 'http://localhost:8000/api/auth/profile/';
    const bookmarkURL = 'http://localhost:8000/api/blogs/saved/';

    const profileDataReq = axios({method: 'GET',
                            url: profileURL,
                            headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
                        });
    const bookmarksReq = axios({method: 'GET',
                            url: bookmarkURL,
                            headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
                        });
    const resp = await axios.all([profileDataReq, bookmarksReq]);
    const data = axios.spread(function(profile, bookmark) {
        console.log('My profile: ', Profile);
        console.log('Saved blogs: ', saved);
    })
    return {
        props: {   }
    };
};

我的问题是如何从getServerSideProps()return{...} 返回axios 数据,以便在组件中使用它?

【问题讨论】:

    标签: javascript axios next.js


    【解决方案1】:

    对于这个用例,我建议您使用Promise.all 而不是axios.all/axios.spread(他们一直是deprecated)。

    export async function getServerSideProps(ctx) {
        const profileDataReq = axios({
            method: 'GET',
            url: 'http://localhost:8000/api/auth/profile/',
            headers: { cookie: ctx.req.headers.cookie }
        });
        const bookmarksReq = axios({
            method: 'GET',
            url: 'http://localhost:8000/api/blogs/saved/',
            headers: { cookie: ctx.req.headers.cookie }
        });
        const [profile, bookmarks] = await Promise.all([
            profileDataReq,
            bookmarksReq
        ]);
    
        return {
            props: { 
                profile: profile.data,
                bookmarks: bookmarks.data
            }
        };
    };
    

    另请注意,ctx.req 始终在 getServerSideProps 中定义。

    【讨论】:

    • 太好了,效果很好。但是Promise.all() 在这里是如何工作的呢?
    • profileDataReqbookmarksReq 都是 Promise,我们只需使用 Promise.all 等待两者都解决(或其中一个拒绝)。如果 Promise 被拒绝,您可能需要进行额外检查。
    猜你喜欢
    • 2021-06-28
    • 2021-12-08
    • 1970-01-01
    • 2020-04-17
    • 2023-02-12
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多