分布式项目中跨域问题怎么解决
1、我的嘛术铹砾windows主机ip是192.168.123.149,装上一个web服务器,如nginx,写一个cors.html页面,然后部署到webr泠贾高框oot目录下,<!DOCTYPE html><html><head><script src="./jquery-1.11.2.js"></script></head><body><h2>演示跨域访问的实现</h2><button onclick="getData();">获取接口数据</button><script>function getData(){$.get("http://192.168.123.41:81/index.php", function (data, status) {alert("Data: " + data + "nStatus: " + status);});}</script></body></html>
2、在windows上面安装virtual box, 然后安装一台ubuntu虚拟机,通过apt-get install nginx-core安装web服务器nginx, 部署一个index.php程序到81端口,内容很简单:---------------------------------------<?phpecho "123";
3、打开浏览器,访问 http://loca盟敢势袂lhost/cors.html,点击获取接口数据的按钮,可以看到浏览器的调试台报错劲忧商偌了。错误信息“Failed to load http://192.168.123.41:81/index.php: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.”,这段话的意思是说 “加载http://192.168.123.41:81/index.php 这个资源的失败, 这个资源没有加Access-Control-Allow-Origin这个http 头,因此不允许从http://localhost这个域去访问http://192.168.123.41:81这个域。“
4、解决方法很简单,只需要在我们的服务端index.php返回的http头部加上header(" Access-Control-Allow-Origin: *");再点击浏览器页面上的按钮,可以看到成功了,弹出了接口返回的数据。