简体   繁体   中英

HTTP interceptor causing CORS issue using ionic/angular

here i am using ionic for web and mobile also and i am using a https url while integrating it i got cors issues .Later when i checked after removing the http interceptor cors issue is resolved but how can i solve this issue below is my code

issues: While using interceptor i am getting CORS issue and if i remove interceptor it is working fine.

export class HttpConfigInterceptor implements HttpInterceptor {
    token:any;

    constructor(public storage: Storage ) { 
        this.storage.get('Token').then(data => {
            this.token = data;
        });
    }


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        //Authentication by setting header with token value
        if (this.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: this.token
                }
            });
        }

        if (!request.headers.has('Content-Type')) {
            request = request.clone({
                setHeaders: {
                    'content-type': 'application/json'
                }
            });
        }

        request = request.clone({
            headers: request.headers.set('Accept', 'application/json')
        });

        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                   
                }
                return event;
            }),
            catchError((error: HttpErrorResponse) => {
                console.error(error);
                return throwError(error);
            }));
    }


}

the request i am getting issue with cors giving 200 and giving text/html

This all sounds to me like your issue is that adding the Authorization header makes a GET request "unsafe" so your client is sending out an OPTIONS preflight request prior to the GET , and your API gateway isn't configured to handle OPTIONS method requests. You probably need to add a generic OPTIONS method handler in your gateway and make sure CORS allows the OPTIONS method.

In any event, this issue is almost definitely on the server side and your server config would be needed to provide a detailed explanation of how to fix this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM