如何在Gatsby中验证用户

时间:2019-04-04 10:55:28

标签: javascript reactjs authentication gatsby

我已按照this教程在我的gatsby项目中实施身份验证。问题是我首先设置了项目,并且路由是从pages文件夹进行的,然后实现了上面的身份验证代码,但是它仍然从 pages 文件夹获取路由,而不是从 app.js 文件中。有人可以帮助我如何从 app.js 而不是从 pages 文件夹中使用组件。

这是我的gatsby-nodejs文件

// Implement the Gatsby API “onCreatePage”. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  // page.matchPath is a special key that's used for matching pages
  // only on the client.
  if (page.path.match(/^\/app/)) {
    page.matchPath = "/app/*"

    // Update the page.
    createPage(page)
  }
}

这是 src / pages.app.js

import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/layout"
import Home from '../components/dashboard/home/container'
import Login from '../components/marketing/home/pulsemetrics'
import { isLoggedIn } from "../services/auth"


console.log('vvvvvvvvvvvvvvvvvvvvv')

const PrivateRoute = ({ component: Component, location, ...rest }) => {
    console.log('hjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiii')
  if (!isLoggedIn() && location.pathname !== `/app/login`) {
    // If the user is not logged in, redirect to the login page.
    navigate(`/app/login`)
    return null
  }

  return <Component {...rest} />
}

const App = () => (
  <Layout>
    <Router>
      <PrivateRoute path="/ddddddddddddddddddd" component={Home} />
      <Login path="/" />
    </Router>
  </Layout>
)

export default App

1 个答案:

答案 0 :(得分:2)

App.js中的路径应该在它们前面加/ app /,因为您的PrivateRoute逻辑使用该路径来检查登录。此外,您的gatsby-node.js文件实际上是在说,对于以app开头的路由,它应该创建一个新页面。您的src / pages / app.js的任务是定义如何创建这些页面(因为它们不是gatsby通常生成的静态页面)

import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/layout"
import Home from '../components/dashboard/home/container'
import Login from '../components/marketing/home/pulsemetrics'
import { isLoggedIn } from "../services/auth"


console.log('vvvvvvvvvvvvvvvvvvvvv')

const PrivateRoute = ({ component: Component, location, ...rest }) => {
    console.log('hjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiii')
  if (!isLoggedIn() && location.pathname !== `/app/login`) {
    // If the user is not logged in, redirect to the login page.
    navigate(`/app/login`)
    return null
  }

  return <Component {...rest} />
}

const App = () => (
  <Layout>
    <Router>
      <PrivateRoute path="/app/home" component={Home} />
      <Login path="/app/login" />
    </Router>
  </Layout>
)

export default App

阅读gatsby客户端专用路由documentation以供参考,或查看此github issue