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');
});
}