跨域请求

一、jsonp跨域请求

注意:用jsonp做跨域请求有两个问题必须注意:

1.jsonp只支持get请求。
2.jsonp属性的值会发送给服务端,服务端接收以后需要在给本地发送数据前加上 这个字符串。一般为:callback。这里用的是 callbackparam

$.ajax({
	type : "get",
	async : false,
	url : "/kyayu/myApp",
	dataType : "jsonp",
	jsonp : "callbackparam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
	data:{"account":"user_box","password":"password_box"},
	success : function(json){
		alert(json[0].name);
	},
	 error: function (jqXHR, textStatus, errorThrown) { 
         alert(textStatus); 
     } 
});

二、cors做跨域请求

JSONP 仅能使用 GET 请求的方式。 对于 RESTful 的 API 来说,发送 POST/PUT/DELET 请求将成为问题,不利于接口的统一。
所以就需要用到cors跨域

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
public class CORSFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// CORS 的域名白名单,不支持正规,允许所有可以用 *
response.addHeader("Access-Control-Allow-Origin", "https://static.ixiaozhi.com");

// 对于非简单请求,浏览器会自动发送一个 OPTIONS 请求,利用 Header 来告知浏览器可以使用的请求方式及 Header 的类型
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1");
}


filterChain.doFilter(request, response);
}


}

该过滤器在 web.xml 中配置:


cors
com.ixiaozhi.filter.CORSFilter


cors
/*

其他,前端的代码使用正常的 Ajax 调用方式就可以,无需关心跨域问题。

原文地址:https://www.cnblogs.com/jixu8/p/5922290.html