Laravel跨域解决方案
- 新建一个中间件
phpartisanmake:middlewareEnableCrossRequestMiddleware
- 书写中间件内容
<?php
namespaceAppHttpMiddleware;
useClosure;
classEnableCrossRequestMiddleware
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
publicfunctionhandle($request, Closure $next)
{
$response = $next($request);
$origin = $request->server("HTTP_ORIGIN") ? $request->server("HTTP_ORIGIN") : "";
$allow_origin = [
"http://localhost:8000",
];
if (in_array($origin, $allow_origin)) {
$response->header("Access-Control-Allow-Origin", $origin);
$response->header("Access-Control-Allow-Headers", "Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN");
$response->header("Access-Control-Expose-Headers", "Authorization, authenticated");
$response->header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, OPTIONS");
$response->header("Access-Control-Allow-Credentials", "true");
}
return $response;
}
}
$allow_origin
数组变量就是你允许跨域的列表了,可自行修改。 - 然后在内核文件注册该中间件
protected $middleware = [
// more
AppHttpMiddlewareEnableCrossRequestMiddleware::class,
];
在
AppHttpKernel
类的$middleware
属性添加,这里注册的中间件属于全局中间件
。
然后你就会发现前端页面已经可以发送跨域请求了。
以上是 Laravel跨域解决方案 的全部内容, 来源链接: utcz.com/z/513362.html