跨域和同源定义:
跨域是指从一个域名的网页去请求另一个域名的资源。比如从www.baidu.com 页面去请求 www.google.com 的资源。但是一般情况下不能这么做,它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。跨域的严格一点的定义是:只要 协议,域名,端口有任何一个的不同,就被当作是跨域
所谓同源是指,域名,协议,端口均相同。这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。
跨域问题会出现如下情况:
利用Nginx反向代理可以解决这一问题。
举一个前后端分离的实例:
将静态文件都存放于 /static/ 文件夹下,nginx具体配置如下:
server { listen 4000; server_name www.aabbccdd.com; charset utf-8; index /static/index.html;//配置首页 #这边可使用正则表达式,拦截动态数据的请求/sellingJson.html,从而解决跨域问题 location = /sellingJson.html { proxy_pass http://192.168.100.17:8090/vueHelpSellingcar.html; } #配置Nginx动静分离,定义的静态页面直接从static读取。 location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ { root /static/; #expires定义用户浏览器缓存的时间为7天,如果静态页面不常更新,可以设置更长,这样可以 节省带宽和缓解服务器的压力 expires 7d; } }
后端对数据的处理:
@RequestMapping("/vueHelpSellingcar.html") public void vueHelpSellingcar(HttpServletRequest request,HttpServletResponse response) { //若干操作后,返回json数据 JSONObject resultJson = new JSONObject(); resultJson.put("carbrandList", carbrandList); resultJson.put("provinceList", provinceList); //进行序列化,返回值前端 byte[] json =resultJson.toString().getBytes("utf-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); response.getOutputStream().write(json); }
前端对数据的处理和展示(使用Axios或者Ajax获取请求结果,本文使用Axios):
//html模块 <div v-if="carbrandList.length" class="char_contain"> <p v-for="brand in carbrandList" id=" {{brand.brand_id}}">{{brand.brand_name}}</p> </div> //js模块 页面加载后,自动去获取动态资源 let v={}; $(function() { axios.get('http://test.csx365.com:4000/sellingJson.html') .then(function(data){ //定义一个vue对象,方便模板渲染 v =Object.assign(v, new Vue({ el : '.char_contain', //绑定事件名 data : { carbrandList : data.data.carbrandList, //数据流 } })); }) .catch(function(err){ console.log(err); }); });
这样就使用Nginx解决了前后端分离的javascript的跨域问题了。
1毛足够感动我!!!