如何使用PHP API将Angular前端与远程MySQL服务器连接?

时间:2019-01-23 06:17:48

标签: mysql angular

login page image

我的本​​地系统中有一个前端前端登录页面。我必须对用户登录进行身份验证。用户数据位于远程服务器中。使用PHP api我需要与远程服务器中的mysql数据库连接以进行身份​​验证。要与之连接的前端代码是什么?

login.component.html

protected void btnLogin_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection(Base.GetConnection))
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM TableUserProfile WHERE UserEmpNum=@UserEmpNum and UserPassword=@UserPassword", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@UserEmpNum", tbEmpNumber.Text);
            cmd.Parameters.AddWithValue("@UserPassword", tbPassword.Text);
            con.Open();
            SqlDataAdapter ad = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            ad.Fill(dt);

            cmd.ExecuteNonQuery();
            if (dt.Rows.Count != 0)
            {
                if (cbRememberLogin.Checked)
                {
                    Response.Cookies["UEmpNo"].Value = tbEmpNumber.Text;
                    Response.Cookies["UPass"].Value = tbPassword.Text;
                    Response.Cookies["UEmpNo"].Expires = DateTime.Now.AddDays(15);
                    Response.Cookies["UPass"].Expires = DateTime.Now.AddDays(15);
                }
                else
                {
                    Response.Cookies["UEmpNo"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["UPass"].Expires = DateTime.Now.AddDays(-1);
                }

                Session["UserEmployee"] = tbEmpNumber.Text;
                Response.Redirect("~/UserProfile.aspx");
            }
        }
    }

login.component.ts

<h1 class="text-center">Login Form</h1>
<div class="container">
    <div class="row">
            <div class="col-xs-10 col-sm-18 col-md-6 col-sm-offset-3 col- 
md-0ffset-4">
                <form #f="ngForm" name="theForm">
                    <div id="user-data">
                      <div class="form-group">

                          <label for="username">UserName</label>
                          <input type="text" id="username"
                          class="form-control"
                          ngModel name="username"
                          required
                          #username="ngModel"
                         >
                          <span class="help-block" *ngIf="!username.valid 
&& username.touched">Enter UserName !</span>
                          <label for="password">Password</label>
                          <input type="password" id="password"
                          class="form-control"
                          ngModel name="password"
                          required
                          #password="ngModel"
                         >
                         <span class="help-block" *ngIf="!password.valid 
&& password.touched">Enter Password !</span>
                      </div>
                      <div class="btn-toolbar">
                          <button class="btn btn-primary " type="submit" 
[disabled]="!f.valid">Login</button>
                          <button class="btn btn-primary" 
type="button">Cancel</button>
                      </div>
                    </div>
                  </form>
              </div>
          </div>
</div>

2 个答案:

答案 0 :(得分:0)

我正在使用类似以下的内容:

在角度方面,我创建了一个api,其中包含与服务器端相关的所有方法,例如登录,注销,添加,编辑...

单击登录按钮后,运行以下命令:

login() {
    //Delete current JWT token if already exists
    localStorage.removeItem('jwt');
    this.auth.loggedIn = false;
    this.showMsg=false;
    //Get username and password
    const user = this.loginGroup.get('username').value;
    const pass = this.loginGroup.get('password').value;

    this.auth.login(user, pass).subscribe(
      (data) => {
        if (data['user_exist'] == 'true') {
          this.showMsg = false;
          //Save the JWT in local storage
          localStorage.setItem('jwt', data['jwt']);
          localStorage.setItem('user_id', data['user_id']);


          //console.log('login component ' + data);
          this.auth.loggedIn = true;

          this.globalVar.user_logged = true;
          this.globalVar.username = data['username'];
          this.globalVar.jwt_token = data['jwt'];
          this.globalVar.user_role = data['user_role'];
          this.globalVar.user_id = data['user_id'];
          this.router.navigate(['dashboard']);
        }
        else {
          this.showMsg = true;
          this.msgTxt = data['errorMsg'];
          if(this.msgTxt=="Incorrect Password!!!")
          {
            this.loginGroup.controls['password'].reset();

            }
            this.globalVar.user_recovery='';
            //console.log(failedAttempt);
          }


          this.auth.loggedIn = false;
        }
      },
      (error) => {
        console.log(error.message)
        if(error.message=="Http failure response for (unknown url): 0 Unknown Error")
        {
          //this.showMsg=true;
          this.msgTxt = "Connection Error. Please try again, when a connection exists";
          this.showMsg=true;
        }
      }
    )
  }

此行:

this.auth.login(user, pass).subscribe()

将转到在angular中创建的api服务,以运行所需的方法并订阅来自服务器的响应:

login(username, password): Observable<any> {
    let headerOptions = new HttpHeaders();
    headerOptions.append('Access-Control-Allow-Origin', '*');
    headerOptions.append('Content-Type', 'application/json');
    headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');


    this.credentials = { user: username, pass: password };
    const httpParams = new HttpParams()
      .set('username', username)
      .set('password', password);


    return this.http.post(this.globalVar.login, httpParams, {
      headers: headerOptions,
    })
  }

您可以在PHP脚本中以$_POST['username']$_POST['password']的形式获取变量。

以下行:

this.globalVar.login

是我在wamp服务器上创建的虚拟主机上的登录代码的URL,看起来像这样:

login = 'http://dev.local/scripts/login.php';

在php方面,脚本很简单。只需检查用户是否存在,然后使用password_hash()(有关如何使用此方法的更多信息,请参见PS)来检查密码是否正确(如果用户存在),然后返回您想要的任何内容(数组,布尔值,文本) ,...)使用json_encode($result)

由于article中提到的原因,在使用PHP和angular时,创建虚拟主机很重要。同一篇文章包含有关如何创建虚拟主机的步骤。

答案 1 :(得分:0)

我一直在同一平台(PHP + MySQL和PHP + Mongo)上工作。

创建POST服务并在此处传递两个参数,我正在考虑从前端发送电子邮件和密码。

  1. HTML

<input type="email" [(ngModel)]="email">
<input type="password" [(ngModel)]="password">
<button (click)="login()">Login</button>

  1. 在login.component.ts 中:

import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login.service';
import { HttpClientModule } from '@angular/common/http';
import * as alertify from 'alertify.js'; // for alerts
import { LocalStorage } from '@ngx-pwa/local-storage'; //for localstorage
import {Router} from "@angular/router"; //to route after successfull login

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  auth : Object; //to store response from api
  email : string; //front end variable
  password : string; //front end variable
  


  constructor(private data : LoginService,protected localStorage: LocalStorage,private router: Router) {
  }

  ngOnInit() {

  }

  login(){

    //console.log(this.email,this.password);

    if(this.email == null && this.email == undefined && this.email == '' && this.password == null && this.password == undefined && this.password == ''){
      alertify.error('Please enter username and password');
    }
    else
      if(this.email == null || this.email == undefined || this.email == '' || this.password == null || this.password == undefined || this.password == ''){
        alertify.error('Please fill all the fields');
    }
    else
      if(this.email != null || this.email != undefined || this.email != '' || this.password != null || this.password != undefined || this.password != ''){
      this.data.loginService({
        "email":this.email,
        "password":this.password
      }).subscribe(data => {

        let auth = data ;

        if(data == 'false'){
          alertify.error("Invalid Password");  
          //false => response from php api
        }
        else
          if(data == 'user_does_not_exist'){
          //user_does_not_exist => response from php api
          alertify.error("User does not exist");   
        }
        else
          if(data == 'error_fetching_email' || data == 'error_fetching_user'){
          //error_fetching_email , error_fetching_user => response from php api
          alertify.log("Database error !! Please try again later");   
        }
        else
        if(data != '[]' && data != '' && data != undefined && data != null && data != 'false'){
        //if data return value
          this.localStorage.setItem('user', btoa(JSON.stringify(auth[0]))).subscribe(() => {
            alertify.success("Login Successfull !!"); 

  //JSON.stringify convert Object to string then btoa() method of angular to encrypt given string

            this.router.navigate(['/main_nav']);
             
          }, () => {
            alertify.error("Storage error"); 
          });
        }
        else{
          alertify.error("Something went wrong !! Please try again later");        
        } 
      });
    }  
    else{
      alertify.error('Somethings wrong !! Please contact Support Staffs');
    }
    
  }

}

  1. 服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs'; //observables to catch errors
import { retry, catchError } from 'rxjs/operators'; //for handling errors generated by code

import * as alertify from 'alertify.js'; //alert messages check alertyfy.js

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  constructor(private Http : HttpClient) { }

    loginService(data) {
  	  	return this.Http.post('http://localhost:8080/auth/login',data)
  	  	.pipe(
  	       retry(1),
  	       catchError(this.handleError) //will call handleError
  	     );
  	  }

  	   handleError(error) {
  	     let errorMessage = '';
  	     if (error.error instanceof ErrorEvent) {
  	       // client-side error
  	       // errorMessage = `${error.error.text}`;
  	       alertify.error("Connection Problem !! Please try again"); 
  	     }
  	     else{
  	     	alertify.error("Something went wrong !! Please try again later");  	
  	     }
  	     return throwError(errorMessage);
	   }

}

快乐编码:v