Search code examples
laravelvue.jscorsfetchlumen

Cors issues only when send headers


I have vueJS running on http://localhost:8080 and Lumen API running on http://stockprise.test/ . I want to do the following request from vueJS to API:

    async log() {
          await fetch("http://stockprise.test/login", {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            },
            body: JSON.stringify({email:'test@gmail.com',password:'pass123'})
          }).then(
            function(response) {
              return response.text();
            },
            function(error) {
              error.message;
            }
          );
        }

but then I get the following error:

CORS policy

This is the code for Cors in lumen

        class CorsMiddleware
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $response = $next($request);
            $IlluminateResponse = 'Illuminate\Http\Response';
            $SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
            $headers = [
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
                'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers',
            ];
            
            if($response instanceof $IlluminateResponse) {
                foreach ($headers as $key => $value) {
                    $response->header($key, $value);
                }
                return $response;
            }
            
            if($response instanceof $SymfonyResopnse) {
                foreach ($headers as $key => $value) {
                    $response->headers->set($key, $value);
                }
                return $response;
            }
            
            return $response;
        }
    }

And i call the Middleware in the bootstrap/app.php middlewareApp of lumen:

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

When I remove the headers in fetch it works perfectly but it sends the data in the form application/x-www-form-urlencoded so i have to add the "Content-type":"application/json" ... Any help ?


Solution

  • This code i have tried in Lumen and working fine

        $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;