0
votes

I have a problem with angular HTTP module, I have a backend API developed with Lumen (URL: http://localhost/api/public/), protected with a bearer token, but when I try to load JSON response in my angular app (URL: http://localhost:4200/), I have this message in my console :

Failed to load http://localhost/api/public/links: Response to the 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. The response had HTTP status code 401.

I have param my API to say 401 it's Authorization header not found, 402 Bearer token not found and, 403 for the invalid token. (I will change all with a 401 error when my problem will be solved)

I found that it's CORS problem, so I add these lines in my .htaccess :

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

But I still have a 401 error in my console despite the fact that I have an HTTP interceptor which adds authorization header in all my HTTP request :

Failed to load http://localhost/api/public/links: Response for preflight has invalid HTTP status code 401. 

I had not the problem when I test my API with Postman, this is my code:

HTTP interceptor

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor() {}

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

    const req = request.clone({ setHeaders: { Authorization: 'Bearer test' } });

    return next.handle(req);
  }
}

Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

import { Link } from '../class/link';

@Injectable({
  providedIn: 'root'
})
export class LinkService {

  constructor(private http: HttpClient) {}

  private resourceUrl = 'http://localhost/api/public/links';

  getAll (): Observable<Link[]> {
    return this.http.get<Link[]>(this.resourceUrl).pipe(
      retry(3),
      catchError(this.handleError('getAll', []))
    );
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      return of(result as T);
    };
  }
}

Thanks in advance!

2
If you check in your browsers developer tools (F12) network tab, are you receiving the Access-Control-Allow- headers in the response from your server? And have you configured the server to deal with the OPTIONS preflight? - user184994
Yes I receive the 3 headers Access-Control-Allow-* :Access-Control-Allow-Headers: origin, x-requested-with, content-type Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS Access-Control-Allow-Origin: * Cache-Control: no-cache, private Connection: close Content-Length: 32 Content-Type: application/json Date: Sun, 19 Aug 2018 13:46:34 GMT Server: Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.3 X-Powered-By: PHP/7.2.3 - Rémi Taniel
Ah, you may need to add Authorization into your list of allowed headers - user184994
Still the same message, I have these 2 lines in my .htaccess : RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] - Rémi Taniel
It's not Angular issue, you need to configure your Lumen and server config correctly to allow preflight to go through, you may change your question tag. - Chybie

2 Answers

1
votes

i was also stuck on this once but got the useful code , simply follow the steps and your issue will be resolved 1) go to your app->Http->Middleware and create a file named PreflightResponse.php and add the following code into it

    <?php

namespace App\Http\Middleware;

use Closure;

class PreflightResponse
{
    /**
    * Handle an incoming request.
    *
    * @param \Illuminate\Http\Request $request
    * @param \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];

        if ($request->isMethod('OPTIONS'))

        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }

        return $response;
    }
}

2)now go to the bootstrapp/app.php and in the section Register Middleware add the following lines of code. your issue will be resolved..

$app->middleware([
  App\Http\Middleware\PreflightResponse::class,
]); 

Enjoy :)

0
votes

I finally find a solution, here is the middleware to add to your Lumen App to support Angular preflight request :

<?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)
    {
        $response = ($request->isMethod('OPTIONS')) ? response()->json('', 200) : $next($request) ;

        $response->header('Access-Control-Allow-Credentials', 'true');
        $response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        $response->header('Access-Control-Allow-Origin', '*');

        return $response;
    }
}