错误HTTP GET对象列表

时间:2017-08-30 11:47:40

标签: javascript php angular

当我尝试从链接(php服务器)检索对象列表时出现错误。

  

阻止多源请求(跨源请求):“相同   source“策略不允许访问位于的远程资源   http://localhost/eReport/index.php。原因:   CORS中缺少“访问控制 - 授权 - 来源”令牌   “Access-Control-Allow-Headers”CORS标题。

我在这个链接上添加了一个类似这个tuto的标题,但我仍然有这个错误。

你能帮我吗?

我的服务页面:

@Injectable()
export class ReportService{
  private baseUrl: string = 'http://localhost/report/reports.php';

  constructor(private http : Http){}
  getAll(): Observable<Report[]>{
    let report$ = this.http
      .get(`${this.baseUrl}`, { headers: this.getHeaders()})
      .map(mapReports);
      return report$;
  }

  private getHeaders(){
    // I included these headers because otherwise FireFox
    // will request text/html
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
    return headers;
  }
  get(id: number): Observable<Report> {
    let report$ = this.http
      .get(`${this.baseUrl}/report/${id}`, {headers: this.getHeaders()})
      .map(mapReport);
      return report$;
  }

我的php页面

header("Access-Control-Allow-Origin: *"); 
        $tab = array(
        array('id'=> '12', 'name'=> 'test','description' => '2018-04-01','url'=>'../../../assets/img/chat1.png' ),
        array('id'=> '13', 'name'=> 'test','description' => '2018-04-01','url'=>'../../../assets/img/highcharts.png' )
    );

    echo json_encode($tab);


?>

1 个答案:

答案 0 :(得分:0)

如果请求转到为应用程序提供服务的同一台服务器,也许最快的解决方法是将Angular应用中的基本网址更改为/report/reports.php

您的请求无效,因为当客户端发送application/json类型的内容时,浏览器不会立即发送请求。如果您重新启动浏览器,然后观察网络标签,您会注意到GET首先发送OPTIONS请求,而不是Origin: yourserver Access-Control-Request-Method: GET Access-Control-Request-Headers: Content-Type, Accept ,而是包含类似这些标题的标题:

Access-Control-Allow-Origin

在这种情况下,浏览器希望服务器不仅返回Access-Control-Allow-Origin: yourserver (or *) Access-Control-Allow-Methods: GET (or a list eg: GET, POST, OPTIONS) Access-Control-Allow-Headers: Content-Type, Accept (the same headers from above) 标题(您已经在做),而且还要返回以下所有内容:

$_SERVER

因此,您需要读取前一个块中的请求标头,并在设置响应标头时使用它们的值。如果您使用apache_request_headers()方法,则非常简单。您也可以从// set required headers: header("Access-Control-Allow-Origin: $_SERVER[HTTP_ORIGIN]"); header("Access-Control-Allow-Methods: $_SERVER[HTTP_ACCESS_CONTROL_REQUEST_METHOD]"); header("Access-Control-Allow-Headers: $_SERVER[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]"); 超全球中获取它们。

   main 
       LDR R1,#0x07 
       LDR R2,#0x12
       LDR R3,#0x00
       ADD R3,R1,R2 
   END

See this helpful article