CORS Angular 2拦截器

时间:2017-08-30 15:28:09

标签: http cors interceptor angular-http-interceptors

当我要求“api / authenticate”“api / account”时,拦截器会将我发送到http://localhost:8443http://localhost:8443/api/authenticate例如),但在其他情况下(例如“api / plan-reports”)我需要问http://localhost:8443/hermessm/api/plan-reports
 所以我有下面的错误。

有谁知道如何修复它? 在我看来拦截器的错误。拜托,帮助我!

interceptor.ts

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return this.intercept(super.request(url, this.getRequestOptionArgs(options)));
}

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    url = this.updateUrl(url);
    return super.get(url, this.getRequestOptionArgs(options));
}

post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
    url = this.updateUrl(url);
    return super.post(url, body, this.getRequestOptionArgs(options));
}

put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
    url = this.updateUrl(url);
    return super.put(url, body, this.getRequestOptionArgs(options));
}

delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
    url = this.updateUrl(url);
    return super.delete(url, this.getRequestOptionArgs(options));
}

getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
    if (!options) {
        options = new RequestOptions();
    }
    if (!options.headers) {
        options.headers = new Headers();
    }
    options.withCredentials = true;
    return !this.firstInterceptor ? options : this.firstInterceptor.processRequestInterception(options);
}


intercept(observable: Observable<Response>): Observable<Response> {
    return !this.firstInterceptor ? observable : this.firstInterceptor.processResponseInterception(observable);
}

private updateUrl(req: string) {
    if (req.indexOf("api/authenticate") !== -1 || req.indexOf("api/account") !== -1) {
        console.log(environment.gataway + '/' + req)
        return environment.gataway + '/' + req;
    }
    else if (req.indexOf("api/") !== -1) {
            return environment.gataway + '/hermessm/' + req;
    }
    else {
        return req;
    }
}

}

2 个答案:

答案 0 :(得分:1)

原因是我的拦截器。我没有解决这个问题,但我删除了拦截器并将代理服务器添加到我的项目

答案 1 :(得分:0)

似乎您正在使用Web API

目前,浏览器不允许从其他域访问服务,这就是您收到此错误的原因。

您需要安装CORS,因此请在程序包管理器控制台上运行以下命令:

Install-Package Microsoft.AspNet.WebApi.Cors

将以下行添加到webapiconfig.cs文件

  var cors = new EnableCorsAttribute("http://localhost:xxx", "*", "*");
  config.EnableCors(cors);

现在你准备好了