众所周知,HTML5的CORS协议,支持各种request method,远胜于仅支持get方式的JSONP。

但今天,我用CORS协议,却一直不成功。

跨域异常,如图

POST http://10.19.66.52/mts-web/register/sendAuthCode.do 400 (Bad Request) jquery.min.js:1
XMLHttpRequest cannot load http://10.19.66.52/mts-web/register/sendAuthCode.do. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://oasit.cnsuning.com' is therefore not allowed access.

  

然后我在服务器端,设置:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Access-Control-Allow-Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");

  

但一直不可以,报400 响应码。

我观察后台代码,可能阻止服务器响应的,大概

method = RequestMethod.POST    @RequestParam
@RequestMapping(value = "register/sendAuthCode", method = RequestMethod.POST)
public String sendAuthCode(@RequestParam String mobilenum, HttpServletResponse response, HttpServletRequest request) {
Map<String, String> responseMap = purseService.sendAuthCode(HttpUtil.getClientIP(request), mobilenum);

将这两条删掉,果然好了!!!

附前后台写法

前端

$.ajax({
...
type: 'post',
xhrFields:{
'withCredentials': 'true' //允许发送HTTPS,COOKIE等凭证
}
});

  

后台

/**
* CORS跨域
*/
public static final String CORS_REQ_ORIGIN = "Origin";
public static final String CORS_RES_ORIGIN = "Access-Control-Allow-Origin";
public static final String CORS_CREDENTIALS = "Access-Control-Allow-Credentials";
/**
* 根据字符串输出JSON,
* 支持CORS协议类型的跨域
*
* @param jsonString
* @return
*/
public String ajaxJsonCORS(HttpServletRequest request, HttpServletResponse response,String jsonString) {
response.setHeader(WapConstants.CORS_RES_ORIGIN, request.getHeader(WapConstants.CORS_REQ_ORIGIN));
response.setHeader(WapConstants.CORS_CREDENTIALS, "true"); return ajax(response,jsonString, "text/html");
}
05-11 11:07