如何使用 next.js 获取客户端 cookie? [英] How can i get a client side cookie with next.js?

查看:259
本文介绍了如何使用 next.js 获取客户端 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

_app.js

从'next/app'导入应用程序;从反应"导入反应;从 '../lib/apollo' 导入 withData;从../components/layout"导入布局;class MyApp 扩展 App {//静态异步 getInitialProps({ Component, router, ctx }) {//让 pageProps = {};//如果 (Component.getInitialProps) {//pageProps = await Component.getInitialProps(ctx);//}//返回 { pageProps };//}使成为() {const { Component, pageProps, isAuthenticated } = this.props;返回 (<div><Layout isAuthenticated={isAuthenticated} {...pageProps}><组件{...pageProps}/></布局>

);}}导出默认 withData(MyApp);

layout.js

从react"导入React;从../hoc/defaultPage"导入 defaultPage;类布局扩展 React.Component {构造函数(道具){超级(道具);}静态异步 getInitialProps(ctx) {让 pageProps = {};如果(Component.getInitialProps){pageProps = await Component.getInitialProps(ctx);}返回 { pageProps, isAuthenticated };}使成为() {const { isAuthenticated, children } = this.props;返回 (<div>{已认证?(<h2>我已登录</h2>) : (<h2>我没有登录</h2>)}{孩子们}

)}}导出默认 defaultPage(Layout);

defaultPage.js

/* hocs/defaultPage.js */从反应"导入反应;从next/router"导入路由器;从../components/auth"导入身份验证;const auth = new Auth();导出默认页面 =>class DefaultPage 扩展了 React.Component {静态异步 getInitialProps(ctx) {const 登录用户 = process.browser?auth.getUserFromLocalCookie(): auth.getUserFromServerCookie(ctx);const pageProps = Page.getInitialProps &&Page.getInitialProps(ctx);让路径 = ""返回 {...页面道具,登录用户,当前网址:路径,isAuthenticated: !!loggedUser};}使成为() {return <Page {...this.props}/>;}};

我在这里遗漏了什么?

解决方案

我认为客户端和服务器端没有使用相同的 cookie.所以这里是您获取客户端 cookie 的方法,您必须在服务器端请求中附加此 cookie.

static async getInitialProps(ctx) {//这是你想要的客户端 cookieconst cookie = ctx.req ?ctx.req.headers.cookie : 空//如果你使用 fetch,你可以像这样手动附加 cookiefetch('已认证', {标题:{曲奇饼}}}

I can't find a way to get a constant value of isAuthenticated variable across both server and client side with next.js

I am using a custom app.js to wrap the app within the Apollo Provider. I am using the layout to display if the user is authenticated or not. The defaultPage is a HOC component.

When a page is server side, isAuthenticated is set a true. But as soon as I change page - which are client side rendering (no reload) - the isAuthenticated remain at undefined all the way long until I reload the page.

_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} />;
    }
  };

What am I missing here?

解决方案

I think client side and server side are not use the same cookie. So here is how you get client side cookie and you have to attach this cookie in your server side request.

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
        }
    }
}

这篇关于如何使用 next.js 获取客户端 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆