Home > Software design >  CORS ORIGIN problem, In a Laravel project
CORS ORIGIN problem, In a Laravel project

Time:11-14

I have a problem with cors origin in my laravel project, I created cors.php in middwares folder and I declare it in Kernel.php and app/Providers/RouteServiceProvider.php as well... I did everything to solve it in my Laravel project, even in folder config I added a file Cors.php

I'm now wondering if I have to add something in Nginx configuration or Apache configuration ?

I'm hosting my project in hostinger VPS, The version of linux is ubuntu 22.04.5 LTS

Thank you in advance. Regards

Middlewares/Cors.php

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * 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', '*')

    }
}

config/cors.php


<?php

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/*','web/*', 'sanctum/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => ['*'],

    'allowed_headers' => ['*'],

    'exposed_headers' => ['*'],

    'max_age' => 0,

    'supports_credentials' => true

];
I added also this lines to Http/kernel.php


    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'cors'     => \App\Http\Middleware\Cors::class, // added
    ];




 
I in console I have this message ( see pictures ):

and I have this message in console : Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
post.js:42559 You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
scrollspy.js:224 Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at An._activate (scrollspy.js:224:10)
    at An._process (scrollspy.js:191:14)
    at new An (scrollspy.js:80:10)
    at bg_scripts.js:35:9
sb-forms-latest.js:5 Uncaught Error: GET_ELEMENTS:  -> form[data-sb-form-api-token]
    at e (sb-forms-latest.js:5:415)
    at sb-forms-latest.js:5:3777
profile.js:32882 Error: Network Error
    at createError (profile.js:872:15)
    at XMLHttpRequest.handleError (profile.js:754:14)
127.0.0.1:8000/getMessages:1          Failed to load resource: net::ERR_CONNECTION_REFUSED
boxicons.min.css:1          Failed to load resource: the server responded with a status of 404 ()

[enter image description here][1]


[enter image description here][2]


  [1]: https://i.stack.imgur.com/T9DhM.png
  [2]: https://i.stack.imgur.com/7zXtW.png

CodePudding user response:

No Problem, Create a new Middleware and put this line in it:

$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', '*');
$response->headers->set('Access-Control-Allow-Credentials', true);
$response->headers->set('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization');

return $response;

and your problem will be solved

You Can check this repo for more details

CodePudding user response:

are you Building an API with a SPA ? and he will be better if you have some error just provide us.

  • Related