1,java 版
在某个接口的 action 里设置 header 的办法行不通,(猜想)因为跨域了之后就进入不到这块代码。
须要在更在之前,染指
比方:在
HandlerInterceptorAdapter
子类里
preHandle
办法退出:
private void filter (HttpServletRequest request, HttpServletResponse response) {
String origin = request.getHeader("Origin");
List<String> domains = Arrays.asList("http://10.96.113.56:3070",
"http://lps-test.intra.xiaojukeji.com",
"https://10.96.113.56:3070",
);
if(origin != null && domains.contains(origin)){response.setHeader("Access-Control-Allow-Origin", origin);
}
log.info("CorsHelper-doFilter-origin:{}",origin );
// * 不行
// response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
留神的是:response.setHeader(“Access-Control-Allow-Origin”, “*”); 这个不行,不晓得为啥。
如此一来,交互流程是:
浏览器先发 OPTIONS 类型的申请,服务端返回 200,内容为空。而后浏览器再发 GET 申请,浏览器返回失常数据。
2,php 版
能够在接口 action 里显式调用
public static function allowChengYeCors()
{
$allowOrigin = array(
'http://10.96.113.56:3070',
'http://lps-test.intra.xiaojukeji.com',
'https://10.96.113.56:3070',
);
// 跨域拜访的时候才会存在此字段
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (in_array($origin, $allowOrigin)) {header('Access-Control-Allow-Origin:'.$origin); // 上线前改为对指定域凋谢
}
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers:x-requested-with');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
}