本来很简单的一件事情,结果遇上了跨域。。
接触过微信开发的应该知道,获取openid的时候,有一步是这样的:
页面请求服务器获取openid,服务器让页面redirect到微信服务器,微信服务器返回一个code给本地服务器。
然后,redirect的时候,因为是本地请求微信的域名,就跨域了。
然而我设置了Access-Control-Allow-Origin到http头,又试过原生的XHR请求,都提示跨域问题。
提示是这样的:
XMLHttpRequest cannot load https://open.weixin.qq.com/connect/oauth2/authorize? No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XX.eicp.net' is therefore not allowed access.
我的代码是这样的:
var xmlhttp = new XMLHttpRequest();
if (!xmlhttp.setRequestHeader) {
xmlhttp = window.XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 1) {
this.setRequestHeader("Access-Control-Allow-Origin", "*");
} else if (this.readyState == 4 && this.status == 200) {
mui.toast(this);
}
}
xmlhttp.open("GET", "/mobile/weixin/getOpenid", true);
xmlhttp.send();
也试过:
<%
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Content-Type", "text/html; charset=UTF8");
%>