一次跨域请求处理(JAVA-SSH)

电脑的IP地址为192.168.1.200,测试一个简单的demo,只有一个页面,设置为主页直接访问:http://localhost:8080/TestServ1/ 页面中用ajax请求后台数据,一开始可以获取到数据,于是把浏览器的地址改为 http://192.168.1.200:8080/TestServ1/ 再访问,请求数据,发现无数据显示,查看后台也无报错。打开浏览器控制台,发现了报错信息:Access to XMLHttpRequest at 'http://localhost:8080/TestServ1/do_Test1_testFunc1.action' from origin 'http://192.168.1.200:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 原来是浏览器认为发生了跨域请求,拒绝显示返回的数据。浏览器地址localhost:8080与ajax请求地址192.168.1.200:8080虽然都是属于本机(服务器)的,但也算跨域了。解决办法:找到后台返回响应数据的response.getWriter().write(content)之前加上response.addHeader("Access-Control-Allow-Origin", "*") ,效果:

response.addHeader("Access-Control-Allow-Origin", "*");
response.getWriter().write(content);
response.getWriter().flush();

 

你可能感兴趣的:(JAVA,HTML)