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嗎?
對於CORS你可以試試這個GitHub上[回購(https://github.com/barryvdh/laravel-cors)]。這是非常容易使用和在我的項目中工作。 –
此標頭不應存在於請求標頭中:Access-Control-Allow-Origin – schellingerht
同意上述規定。對我來說,它必須是全球中間件組的一部分 – tam5