Angular 4 映射函数中的 CORS 错误通过 php

CORS Error in Angular 4 map function through php

我正在从事 Angular4 项目。

为了测试,首先我对任何 json api 完成了 get 请求并且它运行良好。

现在我正在连接 php 文件并进行测试。在 test.php 我有

echo "string";

现在在控制台中我收到此错误:

XMLHttpRequest cannot load http://localhost/php-file/test/test.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

我也附上了它的截图。我用谷歌搜索了它,但无法找到任何解决方案。

然后我编辑了 test.php,如下所示。这是正确的做法吗?

<?php
      header("Access-Control-Allow-Origin: *");
      $data = ['news','dfdf','ddd'];
      echo  json_encode($data);
?>

这就是您需要做的。您还需要在 angular 中包含 headers。

import { Http, Headers, Response, RequestOptions } from '@angular/http';


 headers = new Headers();
      requestOptions = new RequestOptions();
      this.headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
      this.headers.append('Cotent-Type', 'application/json');
      this.requestOptions.headers = this.headers;

      return this.http.post("http://localhost/php-file/test/test.php",  this.requestOptions).map‌​(res => res.json());

这就是您提出 post 请求的方式。确保订阅此调用,然后您可以从 return.

获取数据

希望对您有所帮助。