设置Access-Control-Allow-Origin,解决多域名跨域问题
项目中为了测试方便,通常将Access-Control-Allow-Origin设置为“*”,在项目上线时再改为真实域名。
方法简单粗暴!之后用到一个WangEditot富文本编辑器,上传图片需要确定具体的Access-Control-Allow-Origin,导致在测试图片上传功能时较为麻烦。
通过网上搜索,找到了解决方法:
1、设置多个可跨域域名数组
2、通过request的getHeader(“Origin”)获取origin
3、请求域名属于可跨域域名数组,将所取的orgin值设给Access-Control-Allow-Origin
// 跨域域名设置 public static final String[] ALLOW_DOMAIN = { "http://localhost:8000", "http://192.168.0.100" };
HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String originHeader = req.getHeader("Origin"); if (Arrays.asList(Constants.ALLOW_DOMAIN).contains(originHeader)) { res.setHeader("Access-Control-Allow-Origin", originHeader); res.setHeader("Allow", "*"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); res.setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Authorization, X-Auth-Token"); res.setHeader("Access-Control-Max-Age", "3600"); // 接收跨域的cookie res.setHeader("Access-Control-Allow-Credentials", "true"); if ("IE".equals(req.getParameter("type"))) { ((HttpServletResponse) response).setHeader( "XDomainRequestAllowed", "1"); } if (req.getMethod().toLowerCase().equals("options")) { res.setHeader("Content-type", "text/html"); res.getWriter().write("options OK"); return; } }
更多关于云服务器,域名注册,虚拟主机的问题,请访问西部数码官网:www.west.cn