公司项目之前在做前后端项目 对于ajax跨域问题是这样处理的
1.后端java控制输出流
response.setContentType("text/html;charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin","*");
2.前端直接使用jsonp请求
最近新开了一个项目,做一个全局跨域处理
<mvc:cors> <mvc:mapping path="/**" allowed-origins="*" allowed-methods="POST, GET, OPTIONS, DELETE, PUT" allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" allow-credentials="true" /> </mvc:cors>
上述配置可以针对所有使用springMVC @ResponseBody 的接口
但是在开发过程中,因为使用到拦截器,当不符合条件的时间,需要直接返回数据,终止跳转,所以通过流的形式,直接返回数据。
本来最开始的设置是这样
response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin","*");//'*'表示允许所有域名访问,可以设置为指定域名访问,多个域名中间用','隔开 response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
结果还是不能,报错
Failed to load http://192.168.1.75:8888/api/user/logout: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://192.168.1.25:8081' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
ajax还是请求跨域报错
因为不想通过写死域名的形式,来限制域名,所以最后的设置如下
response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));这样可以适配所有域名