简体   繁体   中英

Angular IO with Laravel Lumen PHP API CORS issue

I'm using Laravel Lumen as a PHP REST Service API, integrated with Angular IO application. Testing the endpoints from Postman, work well. When using a staging live domain and trying to make the endpoints call from the Angular Application to the API, i get CORS errors, although the headers are set from Lumen side with a middleware class.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://sub-domain.ext (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.sub-domain.ext. (Reason: CORS request did not succeed).

Access to XMLHttpRequest at 'http://api.sub-domain.ext' from origin 'http://sub-domain.ext' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The CORS headers have been set from Lumen using a middleware as below:

//Http/Middleware/CorsMiddleware.php

class CorsMiddleware
{
    /**
     * 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, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Authorization, X-Requested-With');        
    }
}

//bootstrap/app.php

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

When hitting the endpoints from the Browser directly, no errors and the output is rendered properly. But when making the call from the live domain/sub-domain (external), i'm getting the CORS errors.

Not sure if anything can be set from Angular side (no ExpressJS used), or it's definitely a server side issue only.

Thank you for your suggestions.

The issue was definitely from the Laravel side, in the .htaccess file,

# Redirect Trailing Slashes If Not A Folder..

It does not accept the '/' at the end of the endpoint if it's not a folder, ie <URL/URI>/?Query_Parameters should be <URL/URI>?Query_Parameters .

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