使用 CORS 方式跨域

什么是CORS

CORS(Cross-Origin Resource Sharing 跨源资源共享),当一个请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。

===前端

  1. 不需要携带cookies,authorization,则前端无需配置
  2. 需要携带cookies,authorization,前端的XMLHttpRequest.withCredentials属性需要设置为true。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

 使用axios的话,其已经进行封装,可以直接设置withCredentials

axios.defaults.withCredentials = true;

===服务端

  1. 添加允许跨域请求的域名(Access-Control-Allow-Origin)

需要配置:1.允许跨域请求的域;2.允许携带的头部;3.允许携带cookies,authorization

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header("Access-Control-Allow-Headers: VERSION,token,If-Modified-Since,currentcity,currentprovince, Content-Type");
header("Access-Control-Allow-Methods: HEAD,GET,POST,DELETE,PUT,OPTIONS");

$allow_origin = array(
    'https://localhost:8090'    // 本地调试跨域则需要本地请求地址
);
if (in_array($origin, $allow_origin)) {
    header('Access-Control-Allow-Origin:' . $origin);
    header('Access-Control-Allow-Credentials:true');
    header('Access-Control-Allow-Headers: Origin,Accept, Authorization, X-Request-With,VERSION,token,currentcity,currentprovince, Content-Type');

}

header("Access-Control-Allow-Headers: VERSION,token,If-Modified-Since,currentcity,currentprovince, Content-Type");
header("Access-Control-Allow-Methods: HEAD,GET,POST,DELETE,PUT,OPTIONS");

$allow_origin = array(
    'https://localhost:8090'    // 本地调试跨域则需要本地请求地址
);
if (in_array($origin, $allow_origin)) {
    header('Access-Control-Allow-Origin:' . $origin);
    header('Access-Control-Allow-Credentials:true');
    header('Access-Control-Allow-Headers: Origin,Accept, Authorization, X-Request-With,VERSION,token,currentcity,currentprovince, Content-Type');

}

不添加,则前端会报错,所请求的资源的允许跨域请求的域没有当前的域名。

使用http协议,Access-Control-Allow-Origin可以设置为*,Access-Control-Allow-Headers也可以不设置; 使用https协议,Access-Control-Allow-Origin必须设置为特定的域名,Access-Control-Allow-Headers也必须设置为特定字段。

  1. 禁止OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

后端不禁止,会将options请求错误处理,发生找不到路由的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值