对预检请求的响应未通过Angular 2的访问控制检查

时间:2016-12-15 18:46:08

标签: javascript angular cors

我正在尝试使用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

1 个答案:

答案 0 :(得分:2)

飞行失败的原因是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