可怕的CORS错误:
跨源请求被阻止:相同的原产地策略不允许在http:/localhost/mySite/api/test。(原因:CORS标题“访问-控制-允许-起源”丢失)。
Laravel路线:
$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
$router->get('/test', 'MyController@myMethod');
});
Laravel Cors Midlware:
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 Kernel:
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
}
)
}
}
});
如果我取出授权头选项,请求就能工作。
发布于 2018-07-05 15:29:51
显然不是理想的解决方案,但它有效。我已经将它添加到了我的processes.php文件的顶部:
header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );
更新:原来是IIS相关的。最后,我在web.config文件中设置了标题,现在CORS可以工作,而无需侵入Broades.php文件。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
</customHeaders>
</httpProtocol>
如果要限制访问,可以添加:
<outboundRules>
<clear />
<rule name="AddCrossDomainHeader">
<match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="true">
<add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?somesite\.com|(.+\.)?anothersite\.org))" />
</conditions>
<action type="Rewrite" value="{C:0}" />
</rule>
</outboundRules>
发布于 2018-07-05 17:05:13
你的中间件是可以的,但是你需要在全局HTTP中间件堆栈中注册CORS中间件。
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\CorsMiddleware::class
];
https://stackoverflow.com/questions/-100005553
复制相似问题