angular:httpClient请求被调用两次

时间:2018-01-02 11:26:24

标签: angular http typescript httpclient

我试着打电话给我的api如下:

MyComponent.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { Api } from '../../services/Api';
import { Account } from '../../models/Account';

@Component({
  selector: 'app-account-individual',
  templateUrl: './account-individual.component.html',
  styleUrls: ['./account-individual.component.css']
})
export class AccountIndividualComponent implements OnInit {

  account_id: number;
  account: Account = new Account();

  constructor(private route: ActivatedRoute, private proxy: Api) {
    this.proxy.postClient('api-get?call=get-account', { "id": 1 }).subscribe(
      res => {
        console.log(res);
      }
    );
  }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.account_id = params['id'];
    });
  }
}

Api.ts:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import * as Globals from 'Globals';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class Api {

    api_url = "http://localhost/MyProject/";

    constructor(private http: Http, private httpClient: HttpClient) { }

    fetchData(url) {
        return this.http.get(this.api_url + url).map(this.extractData).catch(this.handleErrorPromise);
    }

    postClient(url: string, data?: any){
        return this.httpClient.post(this.api_url + url, data);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body||{};
    }

    private handleErrorObservable(error: Response | any) {
        console.error(error.message || error);
        return Observable.throw(error.message || error);
    }

    private handleErrorPromise(error: Response | any) {
        console.error(error.message || error);
        return Promise.reject(error.message || error);
    }
}

服务器CORS:

public function actionApiGet($call){
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: x-test-header, Origin, X-Requested-With, Content-Type, Accept');
        $data = json_decode(file_get_contents('php://input'), true);
...

但api被调用两次,第一个调用方法是OPTIONS,而第二个调用方法是POST

1 个答案:

答案 0 :(得分:2)

如果您正在调用托管在其他服务器中的某个服务,这是预期的行为,浏览器需要验证当前客户端是否托管在有效的服务器中