我試圖使用Angular 2連接到API。我無法連接到它,因爲它給我一個OPTIONS
錯誤以及:對預檢請求的響應未通過對Angular 2的訪問控制檢查
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
我有Google Chrome插件以及標頭。下面是代碼
map.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MapService {
private headers = new Headers();
constructor(private http: Http) { }
getMarkers() {
this.headers.append("Access-Control-Allow-Origin", '*');
this.headers.append("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
this.headers.append("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token');
this.headers.append("Authorization", 'Bearer ' + 'mysecretcode');
return this.http.get('https://api.yelp.com/v3/businesses/search?location=suo&limit=50', { headers: this.headers})
.map(response => response.json());
}
}
map.component.ts
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Marker } from '../../models/map/marker';
import { MapService } from '../../services/map/map.service';
import {Observable} from 'rxjs/Rx';
import {Http, Response, Headers } from '@angular/http';
@Component({
moduleId: module.id,
selector: 'map-view',
templateUrl: 'map.component.html',
styleUrls: ['map.component.css'],
})
export class MapComponent {
marker: Object;
constructor(mapService: MapService) {
mapService.getMarkers()
.subscribe(
marker => this.marker = marker,
error => console.error('Error: ' + error),
() => console.log('Completed!')
);
}
我明白,這是最有可能與CORS問題。這是我可以做些什麼來解決或者這是在結束嗎?
編輯:
這裏是錯誤之一:
Error: Response with status: 0 for URL: null(anonymous function) @ map.component.ts:24SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.error @ Subscriber.ts:202Subscriber._error @ Subscriber.ts:139Subscriber.error @ Subscriber.ts:109Subscriber._error @ Subscriber.ts:139Subscriber.error @ Subscriber.ts:109onError @ http.umd.js:1186ZoneDelegate.invokeTask @ zone.js:262onInvokeTask @ core.umd.js:7768ZoneDelegate.invokeTask @ zone.js:261Zone.runTask @ zone.js:151ZoneTask.invoke @ zone.js:332
運行Chrome瀏覽器使用'--no-網絡security'標誌。 – 2016-12-15 18:47:51
@torazaburo給了這個嘗試沒有運氣。 – Lewis
你必須查看細節。例如,您還需要指定'--user-data-dir'選項,並且它必須是一個乾淨的新的Chrome實例,例如,啓動時您的計算機上不能運行任何Chrome進程。 – 2016-12-15 19:25:48