前端站点A:vue.xx.com
后端站点B:api.xxx.com
当前端A发起对B的请求时,会出现跨域问题,是因为浏览器的同源策略(即保护非同一域名的访问请求拉去别人的数据)导致的,解决方法简单:
1、JSONP,只支持GET方式,基本已经放弃治疗。
2、CORS,一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
我们采用第二CORS来解决跨域问题!
【首先】API站点B,得允许A站跨域拉取他的数据,有两个配置得开启:
1、laravel8:默认是开启的,只需检查kernel.php中,下面标HandleCors行有没被注释掉!
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
还要检查config/cors.php中下面的配置有没修改过:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
2、站点B的nginx的配置,开启允许跨域。
主要看标红部分,标蓝的token最好加上。
location ~ [^/]\.php(/|$) {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Authorization,token,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'application/x-www-form-urlencoded;charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
【其次】前端站点A需配置反向代理,欺骗浏览器,我是在请求同源域名,你别捣乱啊!
同样有两个配置得注意:
1、拉取数据的接口请求地址,你得改成前端的,比如:你要访问API的登录接口(api.xxx.com/api/login),此处的就得改为:vue.xx.com/api/login
2、站点A的服务器,nginx需要对'/api'的路径的访问请求进行反向代理。
location /api {
#rewrite ^/api/(.*)$ /$1 break; ###注意不是开启此处的重写规则。
proxy_pass http://api.xxx.com; #如果有设定端口,也得加上,比如:http://api.xxx.com:8089
}
到处,问题解决了!
本文介绍了如何解决Vue前端站点与Laravel后端站点之间的跨域问题。通过启用Laravel的CORS中间件和配置nginx允许跨域,以及在前端设置反向代理,成功实现了跨域请求。

721

被折叠的 条评论
为什么被折叠?



