简体   繁体   English

通过php的Angular 4地图函数中的CORS错误

[英]CORS Error in Angular 4 map function through php

I am working on Angular4 Project.我正在研究 Angular4 项目。

For testing, first I had done the get request to any json api and its worked well.为了测试,首先我已经完成了对任何 json api 的 get 请求并且它运行良好。

Now I am working to connect the php file and testing it.现在我正在努力连接 php 文件并对其进行测试。 In test.php I had在 test.php 我有

echo "string";

Now in console I am getting this error:现在在控制台中,我收到此错误:

XMLHttpRequest cannot load http://localhost/php-file/test/test.php . XMLHttpRequest 无法加载http://localhost/php-file/test/test.php No 'Access-Control-Allow-Origin' header is present on the requested resource.请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:4200 ' is therefore not allowed access.因此,不允许访问 Origin ' http://localhost:4200 '。

I also attached screenshot of it.我还附上了它的截图。 I had googled it but unable to get any solution for this.我已经用谷歌搜索了它,但无法为此找到任何解决方案。

在此处输入图片说明

then I had edited the test.php like below.然后我编辑了 test.php 如下。 Is it right way to do so?这是正确的方法吗?

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

This is how you need to do.这是你需要做的。 You need to include headers in angular as well.您还需要在 angular 中包含标题。

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());

This is how you should make post request.这就是您应该如何发出发布请求。 Make sure to subscribe this call and then you can get data from return.确保订阅此调用,然后您可以从返回中获取数据。

I hope it helps.我希望它有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM