繁体   English   中英

Next.js:无法从 getServerSideProps 返回 axios.all([…]) 数据

[英]Next.js: Can't return axios.all([…]) data from getServerSideProps

我想调用三个 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数据,以便我可以在组件中使用它?

对于这个用例,我建议您使用Promise.all而不是axios.all / axios.spread

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中定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM