0

I have a project that is currently using Vue cli on localhost:8080 then it request to my laravel api at api.sched.local but it gives me a error CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I'm using laravel 8 so it has already a config/cors and this is inside it

return [

/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/

'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

];

and on my axios instance

import axios from 'axios'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';
axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept';

const defaultOptions = {
    headers: {},
}
// var isDevelopment = true;

const instance = axios.create(defaultOptions);

export default instance

I've been stuck on this CORS error for 2 days thanks

NOTE: I am also using laravel passport I dont know if this affect something

jacakal
  • 25
  • 7
  • `Access-Control-Allow-*` are **response** headers that come from the server. They do not belong in your request and in general will more than likely result in errors like _"Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers"_. – Phil May 19 '22 at 00:15
  • so on my axios instance i will remove the `axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';? ` – jacakal May 19 '22 at 00:27
  • Correct. You can also remove the content-type headers since those are the defaults in Axios. You might as well just have `import axios from "axios"; export default axios.create();` – Phil May 19 '22 at 00:43

1 Answers1

0

I also tried this way but read about some where that you have to add a middleware for cors.So i have added a cors middleware in my project.

<?php

namespace App\Http\Middleware;

use App\Language;
use Closure;
use Illuminate\Support\Facades\App;

class Cors
{
    /**
     * 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';
        $SymfonyResponse    = 'Symfony\Component\HttpFoundation\Response';
        $headers            = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'GET, PUT, POST, DELETE, PATCH',
            'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization, Access-Control-Request-Headers',
            'Access-Control-Allow-Credentials' => 'true',
        ];

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

            return $response;
        } else if ($response instanceof $SymfonyResponse) {
            foreach ($headers as $key => $value) {
                $response->headers->set($key, $value);
            }

            return $response;
        }

        return $next($request)
            ->header('Access-Control-Allow-Origin','*')
            ->header('Access-Control-Allow-Methods','GET, POST, PUT, DELETE, OPTIONS');
    }
}

In App\Http\kernel.php =>

$routeMiddleware you can add it => [
'cors' => \App\Http\Middleware\Cors::class
]

Also use this middleware in you api.php.

The same question related to laravel 5 is here for more details :

Laravel 5.1 API Enable Cors

Vinod Patidar
  • 381
  • 4
  • 11