先看效果
折腾很久,之前搜了一大堆结果但没有一个真正能用的:
http://www.jfinal.com/share/260
http://www.jfinal.com/share/1748
http://www.jfinal.com/share/1137
http://www.jfinal.com/share/1024
...
它们都有一个致命的问题:
"Access-Control-Allow-Origin", "*"
这样设置是过不了浏览器 OPTIONS 预检的,浏览器会拦截然后报错:
需要把 "*" 替换成实际的 origin:
public class DemoAppConfig extends JFinalConfig { public void configInterceptor(Interceptors me) { me.add(new Interceptor() { @Override public void intercept(Invocation inv) { Controller controller = inv.getController(); HttpServletRequest request = controller == null ? null : controller.getRequest(); if (request == null) { return; } String origin = request.getHeader("origin"); String corsHeaders = request.getHeader("access-control-request-headers"); String corsMethod = request.getHeader("access-control-request-method"); HttpServletResponse response = controller.getResponse(); response.setHeader("Access-Control-Allow-Origin", StringUtil.isEmpty(origin, true) ? "*" : origin); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", StringUtil.isEmpty(corsHeaders, true) ? "*" : corsHeaders); response.setHeader("Access-Control-Allow-Methods", StringUtil.isEmpty(corsMethod, true) ? "*" : corsMethod); response.setHeader("Access-Control-Max-Age", "86400"); if ("OPTIONS".equals(request.getMethod().toUpperCase())) { controller.renderJson("{}"); return; } inv.invoke(); } }); } }
完整项目见腾讯 APIJSON 的 Demo 项目 APIJSONFinal
https://github.com/APIJSON/APIJSON-Demo/tree/master/APIJSON-Java-Server/APIJSONFinal