Angular 7 POST метод для PHP сервера не работает - PullRequest
1 голос
/ 20 апреля 2019

Я использую HttpClient для отправки данных с Angular 7 на сервер PHP.Реактивная форма берет необходимые данные от пользователя и затем отправляет их на URL со следующими данными:

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-сервер, который принимает запрос POST из приложения Angular 7 со следующим:

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;

    }
}

Ошибка, которую он дает мне в Chrome:

zone.js: 3243 ОПЦИИ http://localhost/petrapharm-backend/create.php 400 (Неверный запрос)

Доступ к XMLHttpRequest в 'http://localhost/petrapharm-backend/create.php' из источника' http://localhost:4200' заблокирован политикой CORS: Ответ на предпечатный запрос не проходит проверку контроля доступа: У него нет статуса HTTP ok.

Я также попытался запустить запрос POST в Insomnia и Postman, но они возвращают следующее хранилище

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

1 Ответ

1 голос
/ 21 апреля 2019

Это связано с политикой браузера CORS. Браузеры могут интерпретировать разные порты как разные источники, поскольку ваш угловой код обслуживается на 4200, а localhost, вероятно, на чем-то вроде 8100, вы увидите эту ошибку в браузере.

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

В качестве обходного пути вы можете попытаться отключить CORS в браузере Chrome, если вы используете Mac, он запускается из терминала:

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

Для окон этот ответ охватывает решение: Отключить ту же политику происхождения в Chrome

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...