Angular 2+服务调用非法返回语句



在异常消息中获取非法返回语句;然而,在控制台窗口中,它抛出了许多错误和警告错误:-对飞行前请求的响应未通过访问控制检查:请求的资源上不存在"access control Allow Origin"标头。原点'http://localhost:4200因此不允许访问。

警告:-跨原点读取阻止(CORB(阻止跨原点响应http://localhost/api/AOData/Token

从API终点输出:-

{"@odata.context":"http://localhost/api/AOData/$metadata#Edm.String","value":"gVynafvIkYcDyR82cGLOTA5zE_iA6cxdf0oxwyEahBrr06eOo5nUDy2YGyC5_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)
}
}

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

CORS问题描述

最新更新