【发布时间】:2019-03-28 17:21:30
【问题描述】:
我在前端使用 Angular 6,在后端使用 PHP (WAMP),我想创建一个登录系统。当有人输入有效凭据时,我希望他被重定向到 http://localhost:4200/home
我有 auth.php 当有人输入有效的用户名/密码和 verify.php 来检查会话变量是否设置时设置会话变量。 虽然应用程序将我重定向到主页,但 verify.php 看不到会话变量。
这些是我的文件:
login-form.component.ts
loginUser(event) {
const target = event.target;
const username = target.querySelector('#username').value;
const password = target.querySelector('#password').value;
this.Auth.login(username, password).subscribe(data => {
if(data.success) {
this.router.navigate(['/home']);
}
else {
window.alert(data.message);
}
});
}
从 html 中获取用户名和密码并将其发送到服务
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
interface myData {
success: boolean,
message: string
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) { }
login(username, password) {
return this.http.post<myData>('http://localhost/angular6-app/api/auth.php', {username, password},
{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
auth.php
include 'config.php';
header('Access-Control-Allow-Origin: http://localhost:4200');
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
$sql = "select * from user where username = '$username'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if($row['username'] == $username && password_verify($password, $row['password'])) //kanei verify me to hash pou exei ginei
{
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
?>
{
"success": true,
"message": "You have logged in"
}
<?php
}
else {
?>
{
"success": false,
"message": "Invalid credentials"
}
<?php
}
}
?>
最后是 verify.php
<?php
session_start();
header('Access-Control-Allow-Origin: http://localhost:4200');
if (isset($_SESSION['loggedin'])) {
?>
{
"success": true,
"message": "You have the right."
}
<?php
}
else {
?>
{
"success": false,
"message": "You DONT have the right."
}
<?php
}
?>
我的 home.component.ts 有这个类,我想在 html 中显示“你有权利”,但它显示“你没有权利”,因为变量 loggedin 未定义。
export class HomeComponent implements OnInit {
message = "Loading..."
constructor(private user: UserService) { }
ngOnInit() {
this.user.getSomeData().subscribe(data => {
this.message = data.message;
})
}
getSomeData() 在 user.service.ts
中实现getSomeData() {
return this.http.get<myData>('http://localhost/angular6-app/api/verify.php');
}
有没有办法解决这个问题,还是我必须使用另一种方法来检查 angular?
谢谢。
【问题讨论】:
标签: php angular session localhost angular6