javascript - 如何使用 next.js 获取客户端 cookie?

标签 javascript reactjs oauth jwt next.js

我找不到使用 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);

布局.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} />;
    }
  };

我在这里想念什么?

最佳答案

我认为客户端和服务器端不使用相同的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
        }
    }
}

关于javascript - 如何使用 next.js 获取客户端 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58750798/

相关文章:

JavaScript 使用 async/await 确保我在实现之前检索值,但仍然返回 'undefined'

reactjs - 将 setstate 钩子(Hook)函数传递给子路由组件。解构错误

javascript - "A network error has occurred"电子邮件/密码注册 Firebase 时出错

java - 为 Oauth 和 Http Basic 身份验证配置 Spring Security

python - 在 Python Appengine 上使用 Httplib2

javascript - 从 URL 问题获取模型

javascript - jsPDF 服务器端 (node.js) 使用 node-jspdf

javascript - 在带有 innerHTML 的 Javascript 中使用引号

javascript - 如何在 1 分钟后使用 javascript 刷新 Repeater?

reactjs - React Semantic-UI : Modal component with Form component? 有可能吗?