使用带环回的ReacJS进行用户身份验证

时间:2017-12-28 01:17:02

标签: reactjs authentication loopback

我正在开发一个小项目,并尝试使用带有Loopback的ReactJS为前端设置用户身份验证。我有用户的登录视图,并且能够注册然后登录,但我试图将其设置到哪里,如果用户未登录,则他们无法查看我在应用程序中的其他页面。我尝试过搜索,并找到了关于如何完成此步骤的非常简洁的文档。我是否需要在路由器中使用Auth,如果他们已登录,我将如何将用户重定向到页面。

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Carlist from './Carlist';
import About from './About';
import Contact from './contact';
import CarlistDetails from './CarlistDetails';
import Addnew from './Addnew';
import EditCar from './EditCar';
import Thanks from './Thanks';
import Login from "./Login";
import AddUsers from "./AddUsers";
const Main = () => (
  <main>
    <Switch>
      <Route exact path='/' component={Login} />
      <Route exact path='/home' component={Carlist} />
      <Route exact path='/about' component={About} />
      <Route exact path='/Thanks' component={Thanks} />
      <Route exact path='/contact' component={Contact} />
      <Route exact path='/AddUsers' component={AddUsers} />
      <Route exact path='/carlist/add' component={Addnew} />
      <Route exact path='/carlist/edit/:id' component={EditCar} />
      <Route exact path='/carlist/:id' component={CarlistDetails} />
    </Switch>

  </main>


)

导出默认主页;

import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

class Login extends Component {

  submitUser(loginUser) {
    axios.request({
      method: 'post',
      url: 'http://localhost:3000/api/Users/login',
      data: loginUser
    }).then(response => {
      this.props.history.push('/home');
    }).catch(err => console.log(err));
  }

  onSubmit(e) {
    const loginUser = {
      email: this.refs.email.value,
      password: this.refs.password.value,
    }
    this.submitUser(loginUser);
    e.preventDefault();
  }






  render() {
    return (
      <div>

        <h1>Login</h1>
        <form onSubmit={this.onSubmit.bind(this)}>
          <div className="input-field">
            <input type="text" name="email" ref="email" />
            <label htmlFor="email">Email</label>
          </div>
          <div className="input-field">
            <input type="text" name="password" ref="password" />
            <label htmlFor="password">  Password</label>
          </div>
          <input type="submit" value="Login" className="btn blue darken-3" />
          <Link className="btn right" to="/AddUsers">Create Account</Link>
        </form>
      </div>
    )
  }
}
export default Login;

1 个答案:

答案 0 :(得分:0)

您需要一个包含登录参数的州。

state = {login: false}

然后只渲染其他路由,登录为真。

<Switch>
  <Route exact path='/' component={Login} />
  {this.state.login && ...}
</Switch>