mostafalaravel
7 months ago
39
2
Vue

CORS erro in laravel vue

Posted 7 months ago by mostafalaravel

hello I have a Lumen API service Listening on http://localhost:8000

also I'm working on a Laravel project witch is running on : http://127.0.0.1:8080

But when I try to use the Lumen API service It returns me this error message :

Access to XMLHttpRequest at 'http://localhost:8000/api/actions?page=1&per_page=25' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

this is the method to call this API :


            actionFilter: function () {
                //console.log('from actionfilter()', this.actionFilterContent.page)

                axios.get(`http://localhost:8000/api/actions`, {
                    params: this.actionFilterContent
                })
                    .then(response => {
                        this.actionsList = response.data;
                        this.total = response.data.total;
                        this.last_page = response.data.last_page
                        console.log(response.data);
                    })
                    .catch(e => {
                        this.errors.push(e)
                    })

            }

In Lumen :

I added the CORS middlware :

<?php
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, 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;
    }
}

Please sign in or create an account to participate in this conversation.