【问题标题】:Next.js server side routingNext.js 服务器端路由
【发布时间】:2017-07-06 14:51:00
【问题描述】:

我有这个代码来检查用户是否通过了身份验证

const withAuth = AuthComponent => {
  class Authenticated extends Component {
    static async getInitialProps (ctx) {
      let componentProps
      if (AuthComponent.getInitialProps) {
        componentProps = await AuthComponent.getInitialProps(ctx)
      }
      return {
        ...componentProps
      }
    }
    componentDidMount () {
      this.props.dispatch(loggedIn())
    }
    renderProtectedPages (componentProps) {
      const { pathname } = this.props.url
      if (!this.props.isAuthenticated) {
        if (PROTECTED_URLS.indexOf(pathname) !== -1) {
          // this.props.url.replaceTo('/login')
          Router.replace('/login')                   // error
        }
      }
      return <AuthComponent {...componentProps} />
    }
    render () {
      const { checkingAuthState, ...componentProps } = this.props
      return (
        <div>
          {checkingAuthState ? (
            <div>
              <h2>Loading...</h2>
            </div>
          ) : (
            this.renderProtectedPages(componentProps)
          )}
        </div>
      )
    }
  }
  return connect(state => {
    const { checkingAuthState, isAuthenticated } = state.data.auth
    return {
      checkingAuthState,
      isAuthenticated
    }
  })(Authenticated)
}

效果很好,但是当我尝试重定向用户时出现此错误:

未找到路由器实例。您应该只在应用的客户端内使用“next/router”。

如果我尝试使用 this.props.url.replaceTo('/login') 我会收到此警告

警告:'url.replaceTo()' 已弃用。使用“next/router”API。

所以这让我发疯了,我想知道是否有办法实现这种重定向,或者在这种情况下控制身份验证的另一种方法只是一个线索会很好。

【问题讨论】:

    标签: javascript reactjs authentication nextjs


    【解决方案1】:

    您可能应该检查您的代码是在服务器端还是在客户端执行。 这样:

    const isClient = typeof document !== 'undefined'
    isClient && Router.replace('/login') 
    

    要处理服务器端的重定向,您只需使用您的服务器即可。 例如:

    server.get("/super-secure-page", (req, res) => {
      // Use your own logic here to know if the user is loggedIn or not
      const token = req.cookies["x-access-token"]
      !token && res.redirect("/login")
      token && handle(req, res)
    })
    

    仅供参考,我受到next.js code example的启发

    【讨论】:

      【解决方案2】:

      我也想在服务器端找到解决方案。 但我通过写“document.location = xxx”在客户端修复它

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2021-08-27
        • 2020-10-17
        • 2018-02-05
        • 2021-01-08
        • 1970-01-01
        • 2020-02-05
        • 2016-06-01
        • 1970-01-01
        相关资源
        最近更新 更多