Angular 7 POST方法到PHP服务器不起作用

时间:2019-04-20 19:57:40

标签: php angular rest

我正在使用HttpClient将数据从Angular 7发布到PHP服务器。 反应形式从用户那里获取必要的数据,然后将其发布到具有以下内容的网址中:

admin.component.ts

constructor(private postMedicineService: MedicineService) { }

 ngOnInit() {
    this.medicineInfo = new FormGroup({
      name: new FormControl(null, Validators.required),
      description: new FormControl(null, Validators.required),
      category: new FormControl(null, Validators.required),
      image: new FormControl(null, Validators.required),
      price: new FormControl(null, Validators.required)
    });
}

  submitMedicineInfo() {
    this.postMedicineService.postMedicine(this.medicineInfo.value)
      .subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );
  }

medicine.service.ts

const postUrl = 'http://localhost/petrapharm-backend/create.php';

@Injectable()
export class MedicineService {

    constructor(private httpClient: HttpClient) { }

    postMedicine(medicine: Medicine) {
        console.log(medicine);
        return this.httpClient.post(postUrl, medicine);
    }
}

medicine-object.service.ts

export interface Medicine {
    name: String;
    description: String;
    category: String;
    image: File;
    price: number;
}

最后,我有一个PHP服务器,它通过以下命令从Angular 7应用程序中接收POST请求:

create.php

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once './database.php';

// instantiate product object
include_once './medicine.php';

$database = new Database();
$db = $database->getConnection();

$product = new Medicine($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));


// make sure data is not empty
if(
    !empty($data->name) &&
    !empty($data->description) &&
    !empty($data->category) &&
    !empty($data->image) &&
    !empty($data->price)
){

    // set product property values
    $product->name = $data->name;
    $product->description = $data->description;
    $product->category = $data->category;
    $product->image = $data->image;
    $product->price = $data->price;

    // create the product
    if($product->create()){

        // set response code - 201 created
        http_response_code(201);

        // tell the user
        echo json_encode(array("message" => "Product was created."));
    }

    // if unable to create the product, tell the user
    else{

        // set response code - 503 service unavailable
        http_response_code(503);

        // tell the user
        echo json_encode(array("message" => "Unable to create product."));
    }
}

// tell the user data is incomplete
else{

    // set response code - 400 bad request
    http_response_code(400);

    // tell the user
    echo json_encode(array("message" => "Unable to create product. Data is incomplete."));
}
?>

medicine.php

<?php
class Medicine{

    // database connection and table name
    private $conn;
    private $table_name = "medicine";

    // object properties
    public $id;
    public $name;
    public $description;
    public $category;
    public $image;
    public $price;

    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    // create product
    function create(){

        // query to insert record
        $query = "INSERT INTO
                " . $this->table_name . "
            SET
                name=:name, description=:description, category=:category, image=:image, price=:price";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->description=htmlspecialchars(strip_tags($this->description));
        $this->category=htmlspecialchars(strip_tags($this->category));
        $this->image=htmlspecialchars(strip_tags($this->image));
        $this->price=htmlspecialchars(strip_tags($this->price));

        // bind values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":description", $this->description);
        $stmt->bindParam(":category_id", $this->category);
        $stmt->bindParam(":created", $this->image);
        $stmt->bindParam(":price", $this->price);

        // execute query
        if($stmt->execute()){
            return true;
        }

        return false;

    }
}

它给我镀铬的错误:

  

zone.js:3243选项http://localhost/petrapharm-backend/create.php 400(错误请求)

     
    

从原点“ http://localhost/petrapharm-backend/create.php”到“ http://localhost:4200”的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。

  

我还尝试在Insomnia和Postman中运行POST请求,但它们返回以下提示

{
    "message": "Unable to create product. Data is incomplete."
}

1 个答案:

答案 0 :(得分:1)

这是由于浏览器的CORS政策引起的。浏览器可以将不同的端口解释为不同的来源,因为角度代码是在4200上提供的,而本地主机可能是在8100之类的上提供的,因此您将在浏览器中看到此错误。

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

要解决此问题,您可以尝试在Chrome浏览器中禁用CORS,如果您使用的是Mac,则可以从终端上运行它:

open -a Google\ Chrome --args --disable-web-security --user-data-dir=""

对于Windows,此答案涵盖了一个解决方案:Disable same origin policy in Chrome