Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman

让人想犯罪 __ 提交于 2019-12-11 01:59:09

问题


I have an Angular 5 application which connects to an PHP API, everything worked ok when testing in local environment (Ubuntu 16.04, Apache2 2.4.18, PHP 7.2.2) but when I deployed the project in my school server (Uubuntu, Apache2 2.4.27, PHP 7.1.11), GET requests are ok but POST requests are turned into OPTIONS requests and Angular displays the error.

ERROR Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }

Request from origin has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have alredy tested the API with Postman and everything works.

Here is the code of the DataService

constructor(public http:Http) {
  this.url = 'http://10.50.67.83/usuario1/Autozone/';
  this.headers = new Headers();
  this.headers.append('Content-Type', 'application/json');
}

postRequisition(client:string, cart:Selected[]) {
  let data:Data;
  data = {client: client, cart: cart};

  return this.http.post(
    this.url + 'api/requisitions/create.php',
    JSON.stringify(data),
  {
    method: 'POST',
    headers: this.headers
  }).map(res => res.json());
}

I have added the ContentType header beacause I'm posting a JSON.

These are the headers included in the php file.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");
header("Accept: application/json;");

来源:https://stackoverflow.com/questions/48844178/angular-4-post-call-to-php-api-fails-but-get-request-work-and-post-requests-wor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!