网站搜索

javascript - 消息: "Http 请求失败响应 http://localhost/post.php: 0 未知错误" & POST http://localhost/post.php net::ERR_FAILED


我正在尝试向我的数据库添加数据,但看不到错误,感觉卡住了。作为 PHP 和 Angular 的初学者,我通过 XAMPP 使用 PHP,并使用 Angular 8。

我们可以在 PHP 文件中为 POST 和 GET 方法创建两个文件吗?

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  getUrl: string = 'http://localhost/test.php';
  postUrl: string = 'http://localhost/post.php';
  product = [];
  reactiveForm = new FormGroup({
    name: new FormControl(),
    lastname: new FormControl(),
    city: new FormControl(),
  });

  constructor(private httpClient: HttpClient, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.getMethod();
  }

  postMethod() {
    let myFormData = new FormData();
    myFormData.append('name', this.reactiveForm.value.name);
    myFormData.append('lastname', this.reactiveForm.value.lastname);
    myFormData.append('city', this.reactiveForm.value.city);

    return this.httpClient.post(this.postUrl, myFormData).subscribe(
      (response) => console.log(response),
      (error) => console.log(error)
    );
  }

  onSubmit() {
    console.log('resulat', this.reactiveForm.value);
    this.postMethod();
  };

  getMethod() {
    this.httpClient.get(this.getUrl).subscribe(data => {
      this.product.push(data);
    }, error => console.error(error));
  };
}

app.component.html

   <form [formGroup]="reactiveForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
      <label class="label">Name</label>
      <input class="input" type="text" formControlName="name"><br>
    </div>

    <div class="form-group">
      <label class="label">LastName</label>
      <input class="input" type="text" formControlName="lastname"><br>
    </div>

    <div class="form-group">
      <label class="label">city</label>
      <input class="input" type="text" formControlName="city"><br>
    </div>

    <button type="submit">Submit</button>

  </form>

post.php

我已经解决了 Get 方法的 Access-Control-Allow-Origin 错误,但它为什么又出现了?

<?php

    header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

    $postdata = file_get_contents("php://input", true);

    $servername = "localhost";
    $username   = "root";
    $password   = "";
    $dbname     = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    //echo "Connected successfully";

    if(isset($_POST['name'])) $name=$_POST['name'];
     else      $name="";

    if(isset($_POST['lastname'])) $name=$_POST['lastname'];
     else      $lastname="";

    if(isset($_POST['city'])) $name=$_POST['city'];
     else      $city="";

     // Add User
     $sql = "INSERT INTO `test_1` (`id`, `name`, `lastname`, `city`) VALUES ('', '$name', '$lastname', '$city')";

    if ($conn->query($sql) === TRUE) {
        $myJSON = json_encode("New user created successfully");
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    mysqli_close($conn);
?>

我更新了我的 PHP 文件,现在出现了以下错误

答案#1

首先,我建议你阅读问题下的评论,那里面有一些关于 SQL 注入和漏洞的非常重要的回答。

其次,回答你的问题。开始阅读错误信息。你的错误信息显示第35行的 $lastname 未定义。这意味着在你的查询中使用了变量 $lastname,但你从未在代码中创建该变量。

如果你阅读你的代码,你会看到这个

if(isset($_POST['lastname'])) $name=$_POST['lastname'];
     else      $lastname="";

    if(isset($_POST['city'])) $name=$_POST['city'];
     else      $city="";

如果设置了帖子姓氏,则覆盖 $name,否则将 $lastname 设置为空,你的城市语句也是同样的道理。意思是只有在没有提交姓氏时,才创建变量 lastname。

如果你使用的是 PHP7 及以上版本,你实际上可以使用 ?? 运算符(空合并运算符),它会为你执行 isset,你可以像这样编写代码

$name = $_POST['name'] ?? '';
$lastname = $_POST['lastname'] ?? '';
$city = $_POST['city'] ?? '';

如果你仍然使用 PHP5+,你的代码没问题,但就个人而言,我更倾向于对这个使用三元运算符,这样再次降低出现问题的可能性

$name = true === isset($_POST['name']) ? $_POST['name'] : '';

现在这非常重要,这就是为什么我说要读评论。有人现在可能会通过类似这样的东西在你的页面上发布数值

$_POST['lastname'] = '\'; DROP TABLE test_1; \'//';

如果发布正确,但你的权限不正确(不是执行 XSS 的专家),它会删除表。在这里,删除表只是你担心的最小问题,真正的危险是数据被提取。

因此,总是明智的做法是转义你的查询参数,最好使用 mysqli 或 PDO 的机制通过使用预处理语句来转义你的查询参数

在 mysqli 中,你的代码大致如下

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

否则你至少可以使用本地的 mysqli 函数

mysqli_real_escape_string ( mysqli $link , string $escapestr ) : string



// Add User
$sql = "INSERT INTO `test_1` (`id`, `name`, `lastname`, `city`) VALUES ('', '" . mysqli_real_escape_string($con, $name) . "', '" . mysqli_real_escape_string($con, $lastname) . "', '" . mysqli_real_escape_string($con, $city) . "')";

此外,如果你的 ID 是自增的,你应该要么不要将其添加到查询中,要么使用 MySQL 关键字 DEFAULT 作为值,而不是空字符串

最后:除了对你的输入进行转义之外,验证它是否符合你的期望可能是明智的,例如名字理论上不应仅由数字组成?

更多关于预处理语句的信息 https://www.w3schools.com/php/php_mysql_prepared_statements.asp

更多关于 PHP 运算符(空合并运算符和三元运算符) https://www.w3schools.com/php/php_operators.asp

个人建议,总是为你的 if 语句使用 {},这样可读性更高,也能避免第二行为什么没有执行的错误。