【问题标题】:Next.js getInitialProps cookiesNext.js getInitialProps cookie
【发布时间】:2019-10-12 10:23:49
【问题描述】:

我遇到了关于从 Next.js 中的 getInitialProps 函数获取数据的问题

场景是这样的:当用户第一次访问页面时,我向远程 API 发出 HTTP 请求,该 API 返回应用程序所需的数据。我在 getInitialProps 方法中发出请求,因为我希望在将内容发送给用户时完全呈现内容。

问题是,当我发出这个请求时,API 会返回一个会话 cookie,我需要将它存储在浏览器中,而不是呈现内容的服务器。此 cookie 必须存在于未来对 API 的客户端请求中。否则,API 会返回 403。

我的问题是:如果我从服务器执行此请求,并且因此响应也返回到服务器,我如何为浏览器设置 cookie,以便我可以向客户端发出请求API?

我尝试操作 cookie 的 domain 选项,但我无法设置另一个域。浏览器会忽略它。

这是我的getInitialProps 的样子:

static async getInitialProps(appContext) {
        const { Component, ctx, router } = appContext;
        const { store } = ctx;
        let pageProps = {};

        if (Component.getInitialProps) {
            pageProps = await Component.getInitialProps(appContext);
        }

        const { hotelId, reservationId } = router.query;

        if (!hotelId || !reservationId) return { pageProps };

        // Fetching reservation and deal data
        try {
            const { data, errors, session } = await fetchData(hotelId, reservationId);

            if (data) {
                store.dispatch(storeData(data));
            }

        // This works, but the domain will be the frontend server, not the API that I connecting to the fetch the data
        if (session) {
            ctx.res.setHeader('Set-Cookie', session);
        }

        // This doesn't work
        if (session) {
            const manipulatedCookie = session + '; Domain: http://exampe-api.io'
            ctx.res.setHeader('Set-Cookie', manipulatedCookie);
        }

            if (errors && errors.length) {
                store.dispatch(fetchError(errors));
                return { errors };
            } else {
                store.dispatch(clearErrors());
                return {
                    ...pageProps,
                    ...data
                };
            }
        } catch (err) {
            store.dispatch(fetchError(err));

            return { errors: [err] };
        }

        return { pageProps };
    }

fetchData 函数只是一个向 API 发送请求的函数。我从响应对象中提取 cookie,然后将其分配给 session 变量。

【问题讨论】:

  • 如果您的 API 在不同的域上,在其他域上设置 cookie 是有问题的,请考虑安全性,如果允许,您可以在 facebook.com 的行为上设置 cookie :]

标签: javascript authentication cookies next.js server-side-rendering


【解决方案1】:

getInitialProps 在客户端和服务器上执行。因此,当您编写获取函数时,您有条件地获取。因为如果您在服务器端发出请求,则必须输入绝对 url,但如果您在浏览器上,则使用相对路径。您必须注意的另一件事是,当您发出请求时,您必须自动附加 cookie。

在您的示例中,您尝试从 _app.js 发出请求。 Next.js 使用 App 组件来初始化页面。因此,如果您想在页面上显示一些秘密数据,请在该页面上进行。 _app.js 是所有其他组件的包装器,您从 _app.js 的 getInitialProps 函数返回的任何内容都将可用于应用程序中的所有其他组件。但是,如果您想在授权后在组件上显示一些秘密数据,我认为最好让该组件获取数据。想象一个用户登录他的帐户,您必须仅在用户登录时获取数据,因此其他不需要身份验证的端点将无法访问该秘密数据。

假设用户登录并且您想要获取他的秘密数据。想象一下你有页面 /secret 所以在那个组件里面我可以这样写:

Secret.getInitialProps = async (ctx) => {
  const another = await getSecretData(ctx.req);

  return { superValue: another };
};

getSecretData() 是我们应该获取秘密数据的地方。获取动作通常存储在 /actions/index.js 目录中。现在我们在这里编写我们的获取函数:

 // Since you did not mention which libraries you used, i use `axios` and `js-cookie`. they both are very popular and have easy api.
    import axios from "axios";
    import Cookies from "js-cookie";


    //this function is usually stored in /helpers/utils.js
    // cookies are attached to req.header.cookie
    // you can console.log(req.header.cookie) to see the cookies
    // cookieKey is a  param, we pass jwt when we execute this function
    const getCookieFromReq = (req, cookieKey) => {
      const cookie = req.headers.cookie
        .split(";")
        .find((c) => c.trim().startsWith(`${cookieKey}=`));

      if (!cookie) return undefined;
      return cookie.split("=")[1];
    };

    //anytime we make request we have to attach our jwt 
    //if we are on the server, that means we get a **req** object and we execute above function.
   // if we do not have req, that means we are on browser, and we retrieve the    cookies from browser by the help of our 'js-cookie' library.
    const setAuthHeader = (req) => {
      const token = req ? getCookieFromReq(req, "jwt") : Cookies.getJSON("jwt");

      if (token) {
        return {
          headers: { authorization: `Bearer ${token}` },
        };
      }
      return undefined;
    };

    //this is where we fetch our data.
    //if we are on server we use absolute path and if not we use relative
    export const getSecretData = async (req) => {
      const url = req ? "http://localhost:3000/api/v1/secret" : "/api/v1/secret";
      return await axios.get(url, setAuthHeader(req)).then((res) => res.data);
    };

这就是你应该如何在 next.js 中实现获取数据

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 2017-11-29
    • 1970-01-01
    • 2019-03-01
    • 2020-04-24
    • 2021-03-14
    • 2020-05-31
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多