Angular 2+服务调用非法返回声明

时间:2018-07-10 15:33:57

标签: angular

在异常消息中获取非法的返回语句; 但是,在控制台窗口中,它引发了许多错误和警告 错误: -对预检请求的响应未通过访问控制检查:所请求的资源上不存在“ Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://localhost:4200”。

警告:-跨域读取阻止(CORB)阻止了跨域响应http://localhost/api/AOData/Token

从API端点输出:-

{ “@ odata.context”: “http://localhost/api/AOData/ $元数据#Edm.String”, “值”: “gVynafvIkYcDyR82cGLOTA5zE_iA6cxdf0oxwyEahBrr06eO5k1nUDy2YGyC5_HtpOoV7mWZKqwaN-egahMtJ-mxUDrdkdA0Zbq6HUb1cgQ1:BlCFV_NYcj3SvnfwZJ2Yom0PPowXBBklcNsd0KLYW7whCym19wAT-6fYwiqiH5btrQ4TJxE1istE3CcDMC1kGU3hn3CN_COENwH4I8BOF6M1”}

import { Injectable} from '@angular/core';
import {Http, Request,RequestMethod, Response, RequestOptions, Headers, ResponseType, ResponseContentType} from '@angular/http';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/operator/map'
import { Observable } from 'rxjs';

@Injectable()

export class ApiHelper {
    private serviceUrl =  'http://localhost/api/AOData';  // get the config file;
    antiForgeryToken = '';
    tempData = [];
    userName = 'test@testing.com';
    apiKey = '19DFD5E7-79F5-423F-873E-D4655D1FED3B';
        constructor(private http : Http) {
            this.getToken();
        }

        getToken(){
             var url = this.serviceUrl + "/Token";
             this.get(url).subscribe(data => this.antiForgeryToken = data);
        }

        get(url: string){
                return this.request(url, RequestMethod.Get);
        }

        post(url : string, body : object) {
            return this.request(url, RequestMethod.Post, body)
        }

        put(url : string, body : object) {
            return this.request(url, RequestMethod.Put, body)
        }

        delete(url : string, body : object) {
            return this.request(url, RequestMethod.Delete, body)
        }

        getHeader(){
            var headers = new Headers({ 'Content-Type': 'application/json' });
            headers.append('Access-Control-Allow-Origin', '*');
            headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
            headers['Authorization'] ='Basic ' + btoa(this.userName + ':' + this.apiKey);
            if (this.antiForgeryToken) {
                headers['X-Antiforgery-Token'] = this.antiForgeryToken;
            }
            return headers;
        }

        request(url: string, method: RequestMethod, inputData?: object){
                var header = this.getHeader();
                var requestOptions = new RequestOptions({
                    url : url,
                    method : method,
                    headers : header
                    //responseType : ResponseContentType.Json
                });

                if(inputData){
                    requestOptions.body = inputData;
                }

    const request = new Request(requestOptions);

            return this.http.request(request)
            .map((res: Response) => res.json())
            .catch((res: Response) => this.onRequestError(res));
                }

        onRequestError(res : Response){
            const statusCode = res.status;
            const body = res.json();
                const error = {
                    statusCode : statusCode,
                    error : body
                }
                return Observable.throw(error)
        }

}

1 个答案:

答案 0 :(得分:0)

您可能希望从后端而不是前端发出此请求。通常无法从前端处理CORS错误,除非您可以将其添加到服务器上的“允许列表”中。看到这个答案:

CORS issue Description