2

I was sending API request from angular it had CORS issue so i fixed it in server using below code(laravel).

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', '*');
    }
}

But, now i changed my angular request it now goes through interceptor and now the CORS issue is back again.

Interceptor code:

import {Injectable, NgModule} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {LoginService} from './login.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: LoginService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
  ]
})
export class InterceptorModule { }

Error:

Failed to load http://127.0.0.1:8000/api/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Note: The API calls are working perfect if interceptor is not there.

Sample API Call

loginUser() {
    const body = new HttpParams()
      .set('password', this.password)
      .set('email', this.email);
    this.http.post<any[]>(this.apiUrl.getBaseUrl() + 'auth/login', body).subscribe(data => {
      console.log(data);
      const status = data['status'];
      if (status === 'success') {
        this.setSuccess(data['message']);
        this.email = '';
        this.password = '';
        this.loginService.setToken(data['token']);
      } else {
        this.setError(data['message']);
      }

    }, err => {
      this.setError('Server error occurred');
    });
  }
Abhishek
  • 1,008
  • 1
  • 16
  • 39

2 Answers2

0

Not sure why your API calls work without the interceptor and not with it, probably an issue related to preflight requests and your PHP backend. However, if your API is public you shouldn't enable CORS for any Origin as it may allow attackers to access your API with impersonated requests (authenticated as the victim). Please take a look at my answer on this question : Angular2 CORS issue on localhost

Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

I had the same problem when I wanted to call a Solr API. When calling the API, a JWT token was added with an interceptor. Then I got the CORS error (without interceptor it worked perfectly).

The solution was to explicitly allow the Authorization header in Solr web.xml in the "allowed headers" section.

Mike
  • 367
  • 4
  • 8