编程语言
首页 > 编程语言> > javascript – Next.js服务器端路由

javascript – Next.js服务器端路由

作者:互联网

我有这段代码来检查用户是否经过身份验证

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

它工作得很好但我在尝试重定向用户时收到此错误:

No router instance found. You should only use “next/router” inside the client side of your app.

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

Warning: ‘url.replaceTo()’ is deprecated. Use “next/router” APIs.

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

解决方法:

您应该检查您的代码是在服务器端执行还是在客户端执行.
这条路:

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的启发

标签:javascript,authentication,reactjs,nextjs
来源: https://codeday.me/bug/20190705/1391038.html