【问题标题】:Error HTTP GET object list错误 HTTP GET 对象列表
【发布时间】:2017-08-30 20:17:09
【问题描述】:

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

多源请求(跨域请求)的阻塞:“同 源”策略不允许访问位于 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);


?>

【问题讨论】:

  • 你遇到了什么错误?
  • 阻止多源请求(跨源请求):“同源”策略不允许访问位于 http://localhost/eReport/index.php 的远程资源。原因:CORS“Access-Control-Allow-Headers”CORS 标头中缺少“Access-control-authorization-origin”令牌。
  • 这是来自您的服务器端,您需要在那里允许跨不同域的请求

标签: javascript php angular


【解决方案1】:

也许最快的解决方法是将 Angular 应用中的基本 URL 更改为 /report/reports.php,如果请求将发送到为应用提供服务的同一服务器。

您的请求不起作用,因为当客户端发送application/json 类型的内容时,浏览器不会立即发送请求。如果您重新启动浏览器,然后观察网络选项卡,您会注意到首先发送的是 OPTIONS 请求而不是 GET,其中包含类似于以下的标头:

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)

因此您需要从前一个块中读取请求标头,并在设置响应标头时使用它们的值。如果你有apache_request_headers() 方法,那就很简单了。您也可以从$_SERVER superglobal 获取它们。

// 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]");

See this helpful article

【讨论】:

    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    相关资源
    最近更新 更多