携带Cookie的跨域不支持通配符域名问题解决方案

我们解决跨域问题,通常是在返回的header上加入内容:

Access-Control-Allow-Origin:*

这么做,可以解决大多数业务场景的问题。

然而当遇到跨域的时候,需要携带cookie,那么浏览器还是会被跨域策略拦截,并且如下报错:

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

意思就是,如果需要跨域需要携带cookie,为了安全,那么不可以使用*通配符接受任意域名,必须手动添加白名单。如果我需要这个白名单,那么我可以直接指定允许跨域的网址:

Access-Control-Allow-Origin:https://www.baidu.com

然而,如果我不确定这个白名单,甚至说不希望使用白名单,还是想实现任意域名请求。那应该怎么解决呢?聪明的我自然会有更好的解决办法:

if (isset($_SERVER["HTTP_ORIGIN"])) {
  header('Access-Control-Allow-Origin:' . $_SERVER["HTTP_ORIGIN"]);
}

 

 
posted @ 2021-12-01 14:19  Mr.白板  阅读(311)  评论(0编辑  收藏  举报