简体   繁体   English

登录表单无法从React中的后端获取数据

[英]Login form cannot get data from back-end in React

in React when I input any value in text field,then Cannot validate user email and password from back-end. 在我在文本字段中输入任何值时,在React中,然后无法从后端验证用户电子邮件和密码。

I register users from react, store those users in back-end but my requirement is when I try to login unregistered user, then show me error user_name and password incorrect. 我从反应中注册用户,将这些用户存储在后端,但我的要求是当我尝试登录未注册的用户时,然后显示错误user_name和密码错误。 But in my case just redirect the page cannot check users from back-end. 但在我的情况下,只是重定向页面无法从后端检查用户。

Please check the code and update the code and also inform me what's the problem in it. 请检查代码并更新代码,并告知我其中的问题。 Thank you in advance. 先感谢您。

user Controller login function in codeIgniter codeIgniter中的用户控制器登录功能

public function login()
  {
      header("Access-Control-Allow-Origin: *");
      header("Access-Control-Request-Headers: GET,POST,OPTIONS,DELETE,PUT");

      $user_email = $this->input->post('user_email');
      $Password   = $this->input->post('Password');

      $row = $this->Usermodel->login_mode($user_email);
      var_dump( $row);
      if (count($row) > 0) {
          //verify password

          if (password_verify($Password, $row['Password'])) {

              $response = array(
                  "status" => 'success',
                  'message' => "User Login successfully"
              );
          } else {

              $response = array(
                  "status" => 'error',
                  'message' => "Password and Username does not match"
              );
          }

      } else {

          $response = array(
              "status" => 'error',
              'message' => 'Account does not exist'
          );

      }

        $this->output->set_content_type('application/json')->set_output(json_encode($response));
  }

user model login function 用户模型登录功能

public function login_mode($user_email){
      $query = $this->db->get_where('users',$user_email);
      echo $query->row_array();
  }

PostData.js PostData.js

export function PostData(type,userData){
  let headers = new Headers();

  let BaseUrl = 'http://localhost/API/UserController/'
  return new Promise((resolve,reject)=>{
    fetch(BaseUrl+type ,{
      method:'post',
      'Content_type':'application/json',
      body:JSON.stringify(userData),
      headers
    })
    .then((response)=>{
      response.json()
    })
    .then((responseJson)=>{
      resolve(responseJson)
    })
    .catch((error)=>{
      reject(error)
    })
  })
}

login.js Reactjs code login.js Reactjs代码

import React, { Component } from 'react';
import { Link,Redirect } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import {PostData} from './PostData';
class Login extends Component {
  constructor(props){
    super(props);
    this.state = {
      user_email:'',
      Password:'',
      redirect :false
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
}

handleSubmit(event){
  event.preventDefault()
  if(this.state.user_email && this.state.Password){
      PostData('login',this.state)
  }
}

handleChange = (event) =>{
  const name  = event.target.name
  const value = event.target.value
  this.setState({ [name]:value })
}
  render() {
    if (this.state.redirect){
      return <Redirect to='/dashboard'/>
    }
    return (
      <div className="app flex-row align-items-center">
        <Container>
          <Row className="justify-content-center">
            <Col md="8">
              <CardGroup>
                <Card className="p-4">
                  <CardBody>
                    <Form  onSubmit={this.handleSubmit} >
                      <h1>Login</h1>
                      <p className="text-muted">Sign In to your account</p>
                      <InputGroup className="mb-3">
                        <InputGroupAddon addonType="prepend">
                          <InputGroupText>
                            <i className="icon-user"></i>
                          </InputGroupText>
                        </InputGroupAddon>
                        <Input type="email" placeholder="Email" name="user_email" value={this.state.user_email} onChange={this.handleChange} autoComplete="username" required />
                      </InputGroup>
                      <InputGroup className="mb-4">
                        <InputGroupAddon addonType="prepend">
                          <InputGroupText>
                            <i className="icon-lock"></i>
                          </InputGroupText>
                        </InputGroupAddon>
                        <Input type="password" placeholder="Password" name="Password" value={this.state.Password} onChange={this.handleChange} autoComplete="current-password" required />
                      </InputGroup>
                      <Row>
                        <Col xs="6">

                          <input  type="submit" color="primary" value="Login" className="px-4" />

                        </Col>
                        <Col xs="6" className="text-right">
                          <Button  color="link"  className="px-0">Forgot password?</Button>
                        </Col>
                      </Row>
                    </Form>
                  </CardBody>
                </Card>
                <Card className="text-white bg-primary py-5 d-md-down-none" style={{ width: '44%' }}>
                  <CardBody className="text-center">
                    <div>
                      <h2>Sign up</h2>
                      <p>welcome here i do many works for you just sign in then start working.</p>
                      <Link to="/register">
                        <Button color="primary" className="mt-3" active tabIndex={-1}>Register Now!</Button>
                      </Link>
                    </div>


        <p>Error:{this.state.error}</p>
                      </CardBody>
                    </Card>
                  </CardGroup>
                </Col>
              </Row>
            </Container>
          </div>
        );
      }
    }

    export default Login;

You should update this part : 你应该更新这个部分:

fetch("http://localhost/API/UserController/Userlogin",options)
    .then(this.setState({
      user_email : '',
      Password   : '',
      redirect   : true
    }))

Instead of redirecting to the dashboard (by setting redirect at true ) regardless the response from the backend (good or bad), you should create a condition depending on the status code received. 无论后端的响应(好的或坏的),都应该根据收到的状态代码创建条件,而不是重定向到仪表板(通过将redirect设置为true )。

For instance, in case of a response with a 200 status, you indeed redirect to Dashboard but if you get another status, you can show an error message to the user for instance 例如,如果响应具有200状态,您确实重定向到Dashboard但如果您获得另一个状态,则可以向用户显示错误消息,例如

First, You need to check the response of the API. 首先,您需要检查API的响应。 Based on that you can navigate the user to the dashboard. 基于此,您可以将用户导航到仪表板。

For Example: 例如:

If login credentials are correct. 如果登录凭据是正确的。 Then I will return the response below 然后我将返回以下回复

{
 error: false,
 message: "User has logged in successfully"
 data: {
  .....
 }
}

If login credentials are Wrong. 如果登录凭据错误。

{
 error: true,
 data: {}
 message: "Please check the Username and Password"
}

You need to modify this part 您需要修改此部分

fetch("http://localhost/API/UserController/Userlogin",options)
.then(res => res.json())
.then(response => {
  if (!response.error) {
    this.setState({
      user_email : '',
      Password   : '',
      redirect   : true
    });
  } else {
    this.setState({
        user_email : '',
        Password   : '',
        redirect   : false
      });
  }
})
.catch(err=>console.log(err))
fetch("http://localhost/API/UserController/Userlogin",options)
.then(this.setState({
  user_email : '',
  Password   : '',
  redirect   : true
}))
.then(res =>console.log(res.json()))
.catch(err=>console.log(err))

The problem is that irrespective of backend response you are setting the redirect true. 问题是,无论后端响应如何,您都将重定向设置为true。 So when it rerenders it will redirect to another page. 因此,当它重新呈现时,它将重定向到另一个页面。 This code redirecting you 此代码重定向您

const state = this.state.redirect;

if(state){
  return <Redirect to="dashboard" />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM