Laravel API CORS mode not working

I did a lot of research and I implemented the following middleware to get around the CORS error I keep getting…

Middleware/Cors.php

<?php
namespace AppHttpMiddleware;
use Closure;

class Cors
{
/**
 * Handle an incoming request.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
        ->header('Access-Control-Allow-Headers', 'content-type');
    }
}

?>

Kernel.php
protected $routeMiddleware = [
    'auth' => AppHttpMiddlewareAuthenticate::class,
    'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
    'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
    'cors' => AppHttpMiddlewareCors,
];

Routes.php
Route::post('/content', array('middleware' => 'cors', 'uses' => '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82d6e7f1f6c2f1e3f4e7">[email protected]</a>'));

This seems to be configured properly. But when I make the request using fetch API…
fetch('http://laravel.dev/content', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin':'*'
        },
        body: JSON.stringify({

        })
    })
    //.then((response) => response.json())
    .then((response) => response.text()) 
    .then((text) => {
        console.log(text);
    });

I still get this error…
Fetch API cannot load http://laravel.dev/content. 
Response to preflight request doesn't pass access 
control check: No 'Access-Control-Allow-Origin' header 
is present on the requested resource.

I tried adding no-cors mode to my fetch response, and it worked, I got an opaque response, but I need cors mode to get a proper request.

It might be worthwhile to note that my App and my Laravel restAPI are located in the same htdocs folder on XAMPP. I’m not sure if this is an issue.

I also tried adding the headers at the top of my Routers.php file but I still get the same error. Can I even configure a restAPI using laravel?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try to remove

->header('Access-Control-Allow-Headers', 'content-type');

in class Cors like this
<?php
   namespace AppHttpMiddleware;
   use Closure;

   class Cors
   {
        /**
        * Handle an incoming request.
        *
        * @param  IlluminateHttpRequest  $request
        * @param  Closure  $next
        * @return mixed
        */
       public function handle($request, Closure $next)
       {
          return $next($request)
           ->header('Access-Control-Allow-Origin', '*')
           ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');

       }
  }

 ?>

It worked for me.I hope it helpfull for you


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x