我使用Laravel构建了一个API,并将其上传到Linux共享主机中,并且当我想将API与我的React SPA一起使用时。它运行良好,但是这次我将我的API Laravel源代码上传到我域中文件夹中的Centos服务器,并且当我想通过React SPA连接到API时,Chrome表示:
已被CORS政策阻止:对预检请求的响应未通过>访问控制检查:>所请求的资源上没有'Access-Control-Allow-Origin'标头。
当我将这些代码添加到htaccess中时:
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
错误更改为:
对预检请求的响应未通过访问控制检查:未通过 具有HTTP正常状态。
我已经安装了 https://github.com/barryvdh/laravel-cors 在Laravel中。
SPA域:web.example.com
API域:example.com/test
我通过将API域更改为主域来对其进行了测试。
我在Centos中激活了mod_header
。
// my kernel with laravel package
protected $middlewareGroups = [
'api' => [
\Barryvdh\Cors\HandleCors::class,
],
];
// my kernel with cors middleware that i created manually
protected $middleware = [
\App\Http\Middleware\Cors::class,
];
// my api route
Route::namespace('Api')->middleware('cors')->group(function () {
答案 0 :(得分:0)
我正在其中一个项目中工作:https://github.com/devinsays/laravel-react-bootstrap/search?q=cors&unscoped_q=cors。
在app / Http / Kernel.php中:
'cors' => \Barryvdh\Cors\HandleCors::class,
在路线中:
// Auth Endpoints
Route::group([
'middleware' => 'cors',
'prefix' => 'api'
], function ($router) {
Route::post('example', 'Auth\ExampleController');
});
在cors / config.php中:
<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
希望这会有所帮助!