Nitin Soni
Nitin Soni

Reputation: 181

CORS Issue with React app and Laravel API

I have a React app which is at http://localhost:3000/ and Laravel API is at http://localhost/blog/public/api/
I get the following error

Access to fetch at 'http://localhost/blog/public/api/auth/signin' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Error Screenshot

Here are the response headers :-

Response Headers Screenshot

I tried via htaccess, https://packagist.org/packages/barryvdh/laravel-cors

Upvotes: 18

Views: 42769

Answers (7)

Ahmed Meshaal
Ahmed Meshaal

Reputation: 119

I just paste the code of headers below in my laravel project specifically at the end of the file

/bootstrap/app.php

.... then the cors error disappear

`header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', '*');
header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials',' true');

return $app;`

Upvotes: 0

Sodruldeen Mustapha
Sodruldeen Mustapha

Reputation: 1271

The below solution should fix the CORS related issue in Laravel.

Step1: Create a new middleware

php artisan make:middleware Cors

Step 2:

Put the below in the created middle to replace the handle method

public function handle($request, Closure $next) {
    return $next($request)
      ->header('Access-Control-Allow-Origin', '*')
      ->header('Access-Control-Allow-Methods', '*')
      ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
      ->header('Access-Control-Allow-Credentials',' true');
}

Step 3:

Then go to Kernel.php file and add this under the The application's global HTTP middleware stack.

p.s. Only the last line with the comment was added, the other other lines exist before.

protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Cors::class,//cors added here 
 ];

Enjoy!

Upvotes: 23

Tucs
Tucs

Reputation: 1

You try insert with attr enctype="multiple/form-data" when you create form

<form method="POST" role="form" enctype="multiple/form-data">
 <div class="form-group">
  <label for="">Username</label>
  <input type="text" class="form-control" id="" name="username" />
 </div>
 <input type="submit" class="btn btn-primary" value="Submit"/>
</form>   

Upvotes: -2

Shivang Gupta
Shivang Gupta

Reputation: 3331

You can enable CORS inside react application itself if you are using CRA(create-react-app). You need to add setupProxy.js file in your src folder.

const proxy =  require("http-proxy-middleware");
module.exports = (app) => {
  app.use(
    "/api/",
    proxy({
      target: "https://target.com/",
      changeOrigin: true,
      pathRewrite: {
        "^/api/": "/"
      },
    })
  );
};

Upvotes: 2

Robert Tirta
Robert Tirta

Reputation: 2911

Laravel 7 supports CORS out of the box through Barry's package

Otherwise install the package by using this composer require fruitcake/laravel-cors

Then publish the config php artisan vendor:publish --tag="cors"

Then modify it as needed.

Here's a working config (careful, this allows every request from other origin):

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => true,
];

Upvotes: 6

Rezrazi
Rezrazi

Reputation: 895

The error you're getting is due to CORS policy headers not being set on your resource (your Laravel API).
I see you know about barryvdh's cors package, could you please check if you've followed the installation process for that package ?

More specifically, having the following in your Http/Kernel.php file:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

or

protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];

The first injects the middleware globally to your app, the second injects it to the api guard, if you have defined your api routes in routes/api.php it should work as well.


Additionally, you could try to publish the package's config with php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider" and change the allowed headers to 'allowedHeaders' => ['*'],

Upvotes: 1

Shubham Shukla
Shubham Shukla

Reputation: 104

In Laravel to access API without CORS error then you need to add CORS PKG in your Laravel Project.

https://github.com/barryvdh/laravel-cors

You can use this to fix this error.

Upvotes: 0

Related Questions