在 Laravel 中,实现跨域访问通常是通过设置 CORS(跨来源资源共享)策略来完成的。在 CentOS 系统上,你可以使用以下方法之一来实现跨域访问:
方法一:使用 Laravel 内置的中间件
php artisan make:middleware CorsMiddleware
app/Http/Middleware/CorsMiddleware.php
,然后修改 handle
方法:public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization');
return $response;
}
这里我们设置了允许所有来源的访问,你可以根据需要修改 Access-Control-Allow-Origin
的值。
app/Http/Kernel.php
文件的 $middleware
数组中:protected $middleware = [
// ...
\App\Http\Middleware\CorsMiddleware::class,
];
现在,你的 Laravel 应用应该已经允许跨域访问了。
方法二:使用 Nginx 配置
如果你使用 Nginx 作为 Web 服务器,你可以在 Nginx 配置文件中添加以下内容来实现跨域访问:
location / {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'X-Requested-With, Content-Type, Accept, Origin, Authorization' always;
# 其他配置...
}
这里我们同样设置了允许所有来源的访问,你可以根据需要修改 Access-Control-Allow-Origin
的值。
修改完成后,重启 Nginx 服务以使更改生效:
sudo systemctl restart nginx
现在,你的 Laravel 应用应该已经允许跨域访问了。