角度:httpClient请求被调用两次
Posted
技术标签:
【中文标题】角度:httpClient请求被调用两次【英文标题】:angular: httpClient request is called twice 【发布时间】:2018-01-02 11:26:24 【问题描述】:我正在尝试按如下方式调用我的 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
【问题讨论】:
这与 Angular 无关。浏览器对 CORS 请求执行此操作。您需要配置您的服务器以正确处理OPTIONS
请求。搜索 CORS 以查找更多详细信息。
@GünterZöchbauer 请检查更新并查看 CORS
有什么问题?您将无法摆脱 OPTIONS 请求,除非您将配置更改为没有 CORS 情况,这意味着 index.html 是从与 this.api_url + url
结果相同的主机和端口加载的。
这是因为不正确的 CORS 修复 enable-cors.org
【参考方案1】:
如果您正在调用托管在其他服务器中的某些服务,这是预期的行为,浏览器需要验证当前客户端是否托管在有效服务器中
【讨论】:
以上是关于角度:httpClient请求被调用两次的主要内容,如果未能解决你的问题,请参考以下文章