CORS Angular 2 interceptor

1.1k views Asked by At

When i ask to "api/authenticate" or "api/account", interceptor sends me to http://localhost:8443 (http://localhost:8443/api/authenticate for example), but in other cases ("api/plan-reports" for example) i need to ask to http://localhost:8443/hermessm/api/plan-reports.
So i have the error below.

Does anyone know how to fix it? It seems to me the error from interceptor. Please, help me!

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

There are 2 answers

1
Sergey Andreev On BEST ANSWER

The reason was my interceptor. I don't resolve this problem, but i removed the interceptor and added proxy-server to my project

5
Ali Adravi On

Seems you are using web API

These days browsers don't allow to access services from other domain that's why you are getting this error.

You need to install CORS, so run following command on you package manager console:

Install-Package Microsoft.AspNet.WebApi.Cors

Add following lines to your webapiconfig.cs file

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

Now you are ready to go