【问题标题】:Auth Nextjs website from getInitialProps with localstorage or cookie and Apollo使用本地存储或 cookie 和 Apollo 从 getInitialProps 验证 Nextjs 网站
【发布时间】:2018-11-28 02:52:49
【问题描述】:

我在 Nextjs 项目的身份验证过程中遇到了一些问题。从example 开始,它将令牌存储在cookie 中,但在checkLoggedIn.js 中,它查询数据库而不是从cookie 中获取令牌。

我想从getInitialProps 中的cookie 或localstorage 中获取令牌,但是在getInitialProps 中,它看不到localstorage,因为它仍在服务器端。有没有更好的方法可以在组件渲染之前对用户进行身份验证?

不确定是否可以在 apollo 客户端中从 getToken 获取令牌。

我当前的代码是

class DashBoard extends React.Component {
  constructor(props) {
    super(props)
  }

  componentDidMount () {
    const decodeToken = verifyToken(localStorage.getItem('KEY'));

    if (!decodeToken.mail) {
        Router.push('/login');
    } else {
        this.props.loginSuccess(decodeToken.name, decodeToken.mail);
    }
  }
  render () {
      return (<div></div>)
  }
}

谢谢

【问题讨论】:

    标签: reactjs apollo nextjs


    【解决方案1】:

    经过几天的研究,这是我为解决这个问题所做的(老实说,这不是最好的文档)

    getInitialProps 中,我从请求中提取了标头并将它们复制到我的fetch 请求中。

    
    Profile.getInitialProps = async ({ req }) => {
    
      const headers = { ...req.headers }
      const url = `http://localhost:3000/api/profile`
    
      const data = await fetch(url, { headers }).then(res => res.json())
    
      return { data }
    }
    
    

    请记住,这只适用于服务器。对于客户端,您可以将{credentials: 'include'} 传递给fetch

    【讨论】:

      【解决方案2】:

      我通过使用nookies 解决了这个问题。它适用于 Next.js 中的服务器端(用于 getInitialProps)和客户端

      【讨论】:

        猜你喜欢
        • 2023-03-07
        • 2018-05-05
        • 2021-02-05
        • 2020-11-29
        • 2020-04-08
        • 1970-01-01
        • 2017-10-05
        • 1970-01-01
        • 2020-08-20
        相关资源
        最近更新 更多