跨域產生原因及處理方式
阿新 • • 發佈:2018-12-10
1.跨域產生原因
當前站點頁面訪問當前站點之外的資源
2.產生跨域例子(直接瀏覽器開啟 訪問localhost:8080的資源)
<!DOCTYPE html> <html> <head> <title>跨域</title> <script src="jquery-1.11.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $.ajax({ url:'http://localhost:8080/test01', type : 'get', dataType : 'text', success:function(data){ console.log(data); }, error:function(data){ console.log("error."); } }); </script> </head> <body> </body> </html>
3.處理方式一
@RequestMapping("/test01")
@ResponseBody
public User test01(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
return new User("test01", 10);
}
4.處理方式二
@RequestMapping("/test01") @ResponseBody @CrossOrigin public User test01() { return new User("test01", 10); }