1、详细错误信息是:
Access to XMLHttpRequest at '[http://appservice.wogame-dev.com/h5/game/getCdkDetail](http://appservice.wogame-dev.com/h5/game/getCdkDetail)' from origin '[http://app.wogame-dev.com](http://app.wogame-dev.com)' has been blocked by CORS policy: Request header field wg-token is not allowed by Access-Control-Allow-Headers in preflight response.
抓包查看http请求和响应,发现已允许跨域。说明跨域设置是成功了,只是HTTP Header缺少了一个字段,导致的报错。
11_30_08__12_07_2018.jpg
2、这里贴出java源码:
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 【跨域拦截器】
*/
@Configuration
public class CorsInterceptor extends HandlerInterceptorAdapter {
@Value("${service.corsOrigin}")
private String corsOrigins = "http://app.wogame-dev.com";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String origin = request.getHeader("Origin");
if (StringUtils.isNotBlank(origin) && corsOrigins.contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, " +
"WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token");
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
/**设备默认值**/
response.setContentType("application/json;charset=UTF-8");
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
}
缺少HTTP Header : WG-Token ,加上就跨域正常了。
PS: 前端报错说域名不一致,注意域名末尾不需要加斜杠
跨域提示错误.png
错误提示已描述得很清楚,自己看仔细即可。
Access to XMLHttpRequest at '[http://appservice.wogame-dev.com/h5/uc/getUserDetail](http://appservice.wogame-dev.com/h5/uc/getUserDetail)' from origin '[http://app.wogame-dev.com](http://app.wogame-dev.com)' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value '[http://app.wogame-dev.com/](http://app.wogame-dev.com/)' that is not equal to the supplied origin
网友评论