Next.js getInitialProps cookies

Next.js getInitialProps cookies,cookies,next.js,Cookies,Next.js,我遇到了一个关于从Next.js中的getInitialProps函数获取数据的问题 场景是这样的:当用户第一次访问页面时,我向一个远程API发出http请求,该API返回应用程序所需的数据。我在getInitialProps方法中发出请求,因为我希望在将内容发送给用户时完全呈现内容 问题是,当我发出此请求时,API会返回一个会话cookie,我需要将其存储在浏览器中,而不是呈现内容的服务器中。此cookie必须存在于将来对API的客户端请求中。否则,API将返回403 我的问题是:如果我正在从

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

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

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

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

我尝试操作cookie的
选项,但无法设置其他域。浏览器只是忽略了它

下面是我的
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,然后将其分配给
会话
变量。

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

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

假设一个用户登录了,你想获取他的秘密数据。假设您有page/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中实现获取数据的方法

如果你的API在不同的域上,那么在其他域上设置cookie是有问题的,从安全角度考虑,如果允许的话,你可以在facebook.com的behave上设置cookie:]