Home > Software engineering >  Lumen - CORS missing allow origin but request suceed
Lumen - CORS missing allow origin but request suceed

Time:10-29

I have a problem with my application Lumen-VueJs

I make a request and the request status is 200 and I receive what I want but on the 'network' the request is blocked. ( screen ) Request blocked in Console

I have on my app a CorsMiddleware that is like that and that is also added in the bootstrap/app.php

<?php

/**
 * Location: /app/Http/Middleware
 */
namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * 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,PATCH,PUT,DELETE,OPTIONS',
            'Access-Control-Max-Age' => '86400',
                        'Access-Control-Allow-Headers' => 'Content-Type,API-KEY'
                ];

        if ($request->isMethod('OPTIONS')) {
            return response()->json('', 200, $headers);
        }

        $response = $next($request);

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

        return $response;
    }
}

These are the headers of my request : Request's headers

I don't understand why I have that error that must be authorized by my Middleware

Thanks in advance for your help !

CodePudding user response:

Summarizing our discussion in the chat, the issue your browser is complaining about is correct. The Access-Control-Allow-Origin header is not sent.

This is because your middleware was not called as you have added your middleware to $app->routeMiddleware with key cors. I assume there is no route that is called cors. From Lumen's GitHub:

These can be global middleware that run before and after each request [$middleware] into a route or middleware that'll be assigned to some specific routes [$routeMiddleware].

As your CORS middleware should be called for all requests, you need to add it to $app->middleware.

  • Related