可怕的 CORS 错误:
跨域请求被阻止:同源策略不允许在 http://localhost/mysite/api/test 读取远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
Laravel 路线:
$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
$router->get('/test', 'MyController@myMethod');
});
Laravel Cors 中间件:
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, Authorization'
];
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;
}
Laravel 内核:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \App\Http\Middleware\CORS::class
];
相关的.htaccess:
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
相关的 Vue.js:
new Vue({
el: '#app',
data: {
//data here
},
http: {
headers: {
"Authorization": "Basic " + "apiKeyHere"
}
},
methods: {
mymethod: function (e)
{
e.preventDefault();
this.$http.get('http://localhost/mysite/api/test').then(
function (response)
{
//do something
}
)
}
}
});
如果我取出 Authorization 标头选项,则请求有效。
我也尝试过 https://github.com/barryvdh/laravel-cors 但仍然没有乐趣。任何帮助表示赞赏!
原文由 suncoastkid 发布,翻译遵循 CC BY-SA 4.0 许可协议
显然不是理想的解决方案,但它有效。我已将此添加到我的 routes.php 文件的顶部:
如果没有破解就可以很好地完成这项工作……唉。
更新:原来是 IIS 相关的。我最终在 web.config 文件中设置了标题,现在 CORS 可以在不破解 routes.php 文件的情况下工作。
如果要限制访问,可以添加出站规则: