我如何通过next.js获取客户端cookie?

问题描述 投票:0回答:1

我找不到使用next.js在服务器端和客户端都获得恒定值isAuthenticated变量的方法

我正在使用自定义app.js将应用程序包装在Apollo Provider中。我正在使用布局来显示用户是否通过身份验证。 defaultPage是一个HOC组件。

[当页面在服务器端时,将isAuthenticated设置为true。但是,一旦我更改页面-这是客户端呈现(不重新加载),则isAuthenticated始终保持未定义状态,直到重新加载页面为止。

_ app.js

import App from 'next/app';
import React from 'react';
import withData from '../lib/apollo';
import Layout from '../components/layout';

class MyApp extends App {
    // static async getInitialProps({ Component, router, ctx }) {
    //     let pageProps = {};
    //     if (Component.getInitialProps) {
    //       pageProps = await Component.getInitialProps(ctx);
    //     }
    //     return { pageProps };
    //   }

    render() {
        const { Component, pageProps, isAuthenticated } = this.props;
        return (
            <div>
                <Layout isAuthenticated={isAuthenticated} {...pageProps}>
                    <Component {...pageProps} />
                </Layout>

            </div>
        );
    }
}

export default withData(MyApp);

layout.js

import React from "react";
import defaultPage from "../hoc/defaultPage";

class Layout extends React.Component {
    constructor(props) {
      super(props);
    }
    static async getInitialProps(ctx) {
      let pageProps = {};
      if (Component.getInitialProps) {
        pageProps = await Component.getInitialProps(ctx);
      }

      return { pageProps, isAuthenticated };
    }
    render() {
      const { isAuthenticated, children } = this.props;
      return (
          <div>
              {isAuthenticated ? (
                  <h2>I am logged</h2>
              ) : (
                    <h2>I am not logged</h2>
              )}
                {children}
            </div>
      )
    }
}

export default defaultPage(Layout);

defaultPage.js

/* hocs/defaultPage.js */

import React from "react";
import Router from "next/router";

import Auth from "../components/auth";
const auth = new Auth();

export default Page =>

  class DefaultPage extends React.Component {

    static async getInitialProps(ctx) {

      const loggedUser = process.browser
        ? auth.getUserFromLocalCookie()
        : auth.getUserFromServerCookie(ctx);

      const pageProps = Page.getInitialProps && Page.getInitialProps(ctx);

      let path = ""
      return {
        ...pageProps,
        loggedUser,
        currentUrl: path,
        isAuthenticated: !!loggedUser
      };
    }

    render() {
      return <Page {...this.props} />;
    }
  };

我在这里想念什么?

javascript reactjs oauth jwt next.js
1个回答
0
投票

我认为客户端和服务器端使用的Cookie不一致。因此,这是获取客户端cookie的方法,并且必须在服务器端请求中附加此cookie。

static async getInitialProps(ctx) {
    // this is client side cookie that you want
    const cookie = ctx.req ? ctx.req.headers.cookie : null

    // and if you use fetch, you can manually attach cookie like this
    fetch('is-authenticated', {
        headers: {
            cookie
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.