您现在的位置是:网站首页 > 心得笔记

跨域技术讲解

盛悦2025-02-2015人围观
简介在项目开发过程中,尤其涉及前后端联调时,常会遇到跨域问题,就这一问题整理记录下

何为跨域

跨域指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制

同源策略

同源指的是协议、域名、端口均相同。

http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)
http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)
http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)
http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)
http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)
localhost和127.0.0.1虽然都指向本机,但也属于跨域。

处理跨域的配置项

header('Access-Control-Allow-Origin:*')允许所有来源访问,*表示接受任意域名的请求
header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS,PATCH')允许的请求类型
header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept, Authorization')允许的请求头信息
header('Access-Control-Allow-Credentials:true')允许携带证书式访问(携带cookie)

解决跨域的方案

1.nginx配置跨域请求
在nginx server配置文件中添加以下命令
add_header Access-Control-Allow-Origin '*' always;
add_header Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With";
add_header Access-Control-Expose-Headers "*";
add_header Access-Control-Allow-Methods "DELETE, GET, HEAD, POST, PUT, OPTIONS, TRACE, PATCH";
if ($request_method = OPTIONS ) {
    return 200;
}
https://blog.csdn.net/weixin_44273388/article/details/124206129
添加后记得重启nginx服务

2.laravel中间件
添加一个处理跨域中间件,创建命令如下:

php artisan make:middleware CrossHttp

在CrossHttp.php文件下的handle方法添加以下命令
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');
header('Access-Control-Allow-Headers:Origin, Content-Type, Cookie, Accept, X-CSRF-TOKEN,token,Authorization');
header('Access-Control-Allow-Credentials:true');
还要在Kernel.php文件下的$middleware添加CrossHttp文件,实现全局跨域