跨域 如何将指定域名添加到白名单

本文介绍了如何在后端和前端处理跨域问题,通过将指定域名添加到白名单来允许跨域请求。首先,讲解了后端如何配置以允许特定域名,接着讨论了JS如何进行相应的设置以完成跨域请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端处理

$allow_url = [
    0 => 'eva.com',
    1 => 'localhost',
];

$refer = $_SERVER['HTTP_REFERER'];

$pattern = '/^(http|https):\/\/?([^\/]+)/i';
preg_match($pattern, $refer, $match);

$demain_name = $match[2];
if (in_array($demain_name, $allow_url)) {
    header("Access-Control-Allow-Origin:{$match[1]}//{$demain_name}");
    header("Access-Control-Allow-Credentials:true");
}

JS处理

	$.ajax({
		type: "POST",
		url: SCOPE + "Home/Index/Index",
		data: {
			id: id
		},
		xhrFields: {
			withCredentials: true
		},
		crossDomain: true,
		async: true,
		success: function(res) {
			var res = JSON.parse(res);
			if(res.errno == 0) {
				alert(res.message);
				window.location.href = 'index.html';
			}
		}
	});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值