我正在为这个问题而苦苦挣扎,我有一个用Laravel开发的API,其中一个端点需要能够对其他发出请求的服务器进行访问,我在这里浏览了多个论坛,但是我找不到解决方案。
这个错误使我排在前面:
Access to fetch at 'http://localhost:8000/api/v1/auth/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
我试图实现一个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)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
在kernel.php中:
protected $routeMiddleware = [
'cors' => \App\Http\Middleware\Cors::class,
在routes.php中:
Route::post('api/v1/auth/signup', 'Api\AuthApiController@signUpUser')->middleware(['cors']);
为什么cors中间件什么也不做? 从服务器端来看,没有错误。