Laravel API CORS mode not working

僤鯓⒐⒋嵵緔 提交于 2019-12-25 16:42:04

问题


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 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', '*')
        ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
        ->header('Access-Control-Allow-Headers', 'content-type');
    }
}

?>

Kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'cors' => App\Http\Middleware\Cors,
];

Routes.php

Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test@save'));

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?


回答1:


Try to remove

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

in class Cors like this

<?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', '*')
           ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');

       }
  }

 ?>

It worked for me.I hope it helpfull for you



来源:https://stackoverflow.com/questions/40617875/laravel-api-cors-mode-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!