【发布时间】:2020-08-16 11:49:38
【问题描述】:
我已经用 Angular 开发了一个 rest Laravel API。
- Laravel:-> 5.7 *
- 角度:-> 8.2.9
- __________Angular CLI:8.3.8
该项目由 2 个文件夹分隔,每个文件夹具有不同的技术。
项目完成后,使用 IONOS 服务器将其移至生产环境。
但是我收到了这个错误:
Access to XMLHttpRequest at 'https://api.alfarim.es/category' from origin 'http://www.alfarim.es' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
app.component.ts:63
HttpErrorResponse
api.alfarim.es/category:1 Failed to load resource: net::ERR_FAILED
1st - 创建子域
- 我将 Laravel 项目上传到一个文件夹中
- 在 IONOS 中创建子域
- 创建指向 Laravel 公用文件夹的子域
- 修改 Angular 的全局变量以匹配子域。
2nd - 中间件
// 我们创建一个中间件
->header('Access-Control-Allow-Origin', '*’)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS’);
//我们进入内核
'cors' => \App\Http\Middleware\Cors::class,
// 添加到路由
Route::group(['middleware' => 'cors'], function(){
//rutes
});
然后进行所有设置
链接:https://github.com/fruitcake/laravel-cors
3rd - 水果蛋糕
安装
composer require fruitcake / laravel-cors
然后进行所有设置
链接:https://github.com/fruitcake/laravel-cors
实际状态
中间件
<?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, DELETE, OPTIONS’);
}
}
内核
protected $middleware = [
....
\Fruitcake\Cors\HandleCors::class,
];
protected $routeMiddleware = [
.....
'cors' => \App\Http\Middleware\Cors::class,
];
cors.php --- 配置
'paths' => ['api/*'],
/*
* Matches the request method. `[*]` allows all methods.
*/
'allowed_methods' => ['*'],
/*
* Matches the request origin. `[*]` allows all origins.
*/
'allowed_origins' => ['*'],
/*
* Matches the request origin with, similar to `Request::is()`
*/
'allowed_origins_patterns' => [],
/*
* Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
*/
'allowed_headers' => ['*'],
/*
* Sets the Access-Control-Expose-Headers response header with these headers.
*/
'exposed_headers' => [],
/*
* Sets the Access-Control-Max-Age response header when > 0.
*/
'max_age' => 0,
/*
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => false,
$app->configure('cors');
];
路线
Route::group(['middleware' => 'cors'], function(){
//.....
Route::post('/api/register/','UserController@register');
});
【问题讨论】:
-
响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。如果 Chrome 没有显示,请改用 Firefox 中的 devtools。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?