2017-07-06 75 views
1

我有这样的代码来检查,如果用户进行身份验证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) 
} 

它的伟大工程,但是当我尝试将用户重定向我得到这个错误:

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

,如果我尝试使用this.props.url.replaceTo('/login')我得到这样的警告

警告: 'url.replaceTo()' 已过时。使用“下一个/路由器”API。

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

回答

0

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

0

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

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

启发
相关问题