对预检请求的响应未通过对Angular 2的访问控制检查
我试图使用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
原因飞行前的失败是一个标准的问题CORS:
How does Access-Control-Allow-Origin header work?
它是固定的通过让服务器设置正确的Access-Control-Allow-Origin。
但是,您的问题的根本原因可能是您的服务器或客户端配置错误,因为500是服务器内部错误。所以它可能不会访问预期的服务器代码,而是一些apache中的通用处理程序或任何托管服务的通用处理程序。大多数通用错误处理程序不提供CORS支持作为默认处理。
请注意,如果您使用的是REST API,则500不是应该在成功的API使用场景中看到的代码。这意味着服务器无法正确处理请求。
也许这个链接就会有相关的信息: EXCEPTION: Response with status: 0 for URL: null in angular2
运行Chrome浏览器使用'--no-网络security'标志。 – 2016-12-15 18:47:51
@torazaburo给了这个尝试没有运气。 – Lewis
你必须查看细节。例如,您还需要指定'--user-data-dir'选项,并且它必须是一个干净的新的Chrome实例,例如,启动时您的计算机上不能运行任何Chrome进程。 – 2016-12-15 19:25:48