js 跨域 之 修改服务器配置-XAMPP-Apache (nginx 拉到最后!)

js高程第21章提到了ajax 跨域技术,方法有很多,如图:

imageimage

我主要讲这个:

image

其实代码就是这样就好了,当然只兼容 IE9 及之后的版本 ,IE9 之前的版本请去原书看吧,Page 600

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
  if (xhr.readyState == 4){
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
      alert(xhr.responseText);
    } else {
      alert("Request was unsuccessful: " + xhr.status);
    }
  }
};
xhr.open("get", "http://www.somewhere-else.com/page/", true);
xhr.send(null);

但是这有个前提:

image

那么如何让服务器返回这个头部,允许跨域请求呢?下面以 XAMPP 的 Apache 服务器为例!(wamperserver 应该类似,nginx 请拉到最后!)

image

选择 Apache (httpd.config),打开

1、找到 LoadModule headers_module modules/mod_headers.so 这个,把前面的 # 删掉 ,我是本来就没有 # ,所以就到下一步;

2、找到这个,我是这样的,可能大家有点不同,

image

改成这样:

image

重点是这个:

Header set Access-Control-Allow-Origin *

*表示允许所有的域访问,当然这是很危险的, 较为安全的配置,应该是直接指定具体的域名。那么就要用 Header add 不是Header set,否则只有最后一行的配置生效,比如

Header add Access-Control-Allow-Origin "www.b.com"  
Header add Access-Control-Allow-Origin "www.c.com"

我这里是本地测试,自然用的 * ( 亲测可以 ), 指定域名的我没试,不保证没问题

但是本人设置 之后,把Apache关掉重启还是失败了,结果关机重启就好了;

nginx 可以参考下文

参考:

https://yq.aliyun.com/articles/41528

原文地址:https://www.cnblogs.com/xianshenglu/p/8401126.html