-
跨域原因产生:在当前域名请求网站中,默认不允许通过ajax请求发送其他域名
-
浏览器默认网站资源 都是必须在同一个资源下的。
通常都是ajax请求不同域名导致的跨域。
这种不会导致跨域
-
解决方案:
a. jsonp解决跨域,但是只支持get请求,不支持post
b. 使用接口网关,在nginx中操作
c. springcloud中使用的zuul(常用方式)
d. 使用httpclient进行内部转发
e. 在header请求头中设置参数允许跨域访问.
response.setHeader(“Access-Control-Allow-Origin”, “*”); -
jsonp解决:
$.ajax({
type : “POST”,
async : false,
url : “http://xxx.yyy.com/zzz/getData?userName=张三”,
dataType : “jsonp”,//数据类型为jsonp
jsonp : “jsonpCallback”,//服务端用于接收callback调用的function名的参数
success : function(data) {
alert(data.result);
},
error : function() {
alert(‘fail’);
}
});
@WebServlet("/getData")
public class FromUserServlet extends HttpServlet {@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding(“UTF-8”);
// resp.setHeader(“Access-Control-Allow-Origin”, “*”);
String userName = req.getParameter(“userName”);
String userAge = req.getParameter(“userAge”);
System.out.println(userName + “----” + userAge+"—"+req.getMethod());
// JSONObject JSONObject1 = new JSONObject();
// JSONObject1.put(“success”, “添加成功!”);
// resp.getWriter().write(“callbackparam(” + JSONObject1.toJSONString()
// + “)”);try { resp.setContentType("text/plain"); resp.setHeader("Pragma", "No-cache"); resp.setHeader("Cache-Control", "no-cache"); resp.setDateHeader("Expires", 0); PrintWriter out = resp.getWriter(); JSONObject resultJSON = new JSONObject(); // 根据需要拼装json resultJSON.put("result", "content"); String jsonpCallback = req.getParameter("jsonpCallback");// 客户端请求参数 out.println(jsonpCallback + "(" + resultJSON.toJSONString() + ")");// 返回jsonp格式数据 out.flush(); out.close(); } catch (Exception e) { // TODO: handle exception }
}
}
jsonp原理:
在同源策略下,在某个服务器下的页面是无法获取到该服务器以外的数据的,即一般的ajax是不能进行跨域请求的。但 img、iframe 、script等标签是个例外,这些标签可以通过src属性请求到其他服务器上的数据。利用 script标签的开放策略,我们可以实现跨域请求数据,当然这需要服务器端的配合。 Jquery中ajax 的核心是通过 XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加
当我们正常地请求一个JSON数据的时候,服务端返回的是一串 JSON类型的数据,而我们使用 JSONP模式来请求数据的时候服务端返回的是一段可执行的 JavaScript代码。因为jsonp 跨域的原理就是用的动态加载 script的src ,所以我们只能把参数通过 url的方式传递,所以jsonp的 type类型只能是get !