2016-11-15 60 views
0

我做了很多的研究,我採取了以下中間件,以繞過CORS錯誤我不斷收到...Laravel API CORS模式不工作

中間件/ 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'); 
    } 
} 

?> 

內核.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' => '[email protected]')); 

這似乎配置正確。但是,當我用做取API我嘗試添加no-cors模式,我獲取響應的請求......

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); 
    }); 

我仍然得到這個錯誤...

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. 

,和它的工作,我得到了一個不透明的響應,但我需要cors模式來獲得正確的請求。

值得注意的是我的App和我的Laravel restAPI位於XAMPP上的同一個htdocs文件夾中。我不確定這是否是一個問題。

我也嘗試在我的Routers.php文件的頂部添加標題,但我仍然得到相同的錯誤。我甚至可以使用laravel配置restAPI嗎?

+0

對於CORS你可以試試這個GitHub上[回購(https://github.com/barryvdh/laravel-cors)]。這是非常容易使用和在我的項目中工作。 –

+0

此標頭不應存在於請求標頭中:Access-Control-Allow-Origin – schellingerht

+0

同意上述規定。對我來說,它必須是全球中間件組的一部分 – tam5

回答

0

嘗試一個Cors刪除

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

這樣

<?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'); 

     } 
    } 

?> 

它的工作對我,我希望它有幫助你