我正在尝试使用Angular 2连接到API。我无法连接到它,因为它给了我一个OPTIONS
错误以及: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的问题。这是我可以解决的问题,还是yelps结束?
编辑:
这是错误之一:
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
最佳答案
飞行前失败的原因是CORS的标准问题:
How does Access-Control-Allow-Origin header work?
通过让服务器设置正确的Access-Control-Allow-Origin可以解决此问题。
但是,问题的根本原因可能是服务器或客户端的配置错误,因为500是服务器内部错误。因此,它可能不是在访问预期的服务器代码,而是在apache中的某个通用处理程序或托管该服务的任何内容。大多数通用错误处理程序默认不提供CORS支持。
请注意,如果您使用的是REST API,则在成功使用API的情况下,不应看到500。这意味着服务器无法正确处理请求。
也许此链接将具有相关信息:
EXCEPTION: Response with status: 0 for URL: null in angular2
关于javascript - 对预检请求的响应未通过Angular 2通过访问控制检查,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41171262/