天天看點

實作跨域

跨域測試

1.浏覽器位址:http://www.jt.com/test.html

2.ajax請求位址:http://manage.jt.com/test.json

結論:

如果請求位址(協定://域名:端口)不相同則導緻請求調用失敗

浏覽器-同源政策說明

說明:浏覽器規定發起ajax時如果請求協定/域名/端口号,如果三者有一個與目前的浏覽器的位址不相同時,則違反同源政策,浏覽器不予解析傳回值。

跨域問題:違反同源政策的規定就是跨域請求。

跨域1-JSNOP

JSONP跨域原理

JSONP(JSON with Padding)是JSON的一種“使用模式”,可用于解決主流浏覽器的跨域資料通路的問題。

1.利用javascrpit中的src屬性實作跨域請求.

2.自定義回調函數 function callback(xxxx);

3.将傳回值結果進行特殊的格式封裝 callback(json);

4.由于利用src屬性進行調用 是以隻能支援get請求類型.

JSONP優化

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSONP測試</title>
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript">
	$(function(){
		alert("測試通路開始!!!!!")
		$.ajax({
			url:"http://manage.jt.com/web/testJSONP",
			type:"get",				//jsonp隻能支援get請求
			dataType:"jsonp",       //dataType表示傳回值類型
			jsonp: "callback",    //指定參數名稱
			jsonpCallback: "hello",  //指定回調函數名稱
			success:function (data){   //data經過jQuery封裝傳回就是json串
				console.log(data);
			}
		});	
	})
</script>
</head>
<body>
	<h1>JSON跨域請求測試</h1>
</body>
</html>
           

編輯後端Controller

package com.jt.web.controller;
import com.jt.pojo.ItemDesc;
import com.jt.util.ObjectMapperUtil;
import jdk.nashorn.internal.runtime.regexp.JoniRegExp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JSONPController {
    /**
     * 實作JSONP跨域請求
     * url位址: http://manage.jt.com/web/testJSONP?callback=xxxxxx
     * 參數:    暫時沒有可以不接
     * 傳回值:  callback(JSON);
     */
     @RequestMapping("/web/testJSONP")
     public String testJSONP(String callback){
         ItemDesc itemDesc = new ItemDesc();
         itemDesc.setItemId(1000L).setItemDesc("JSONP測試!!!");
         String json = ObjectMapperUtil.toJSON(itemDesc);
         return callback+"("+json+")";
     }
}
           

JSONPObject說明

@RequestMapping("/web/testJSONP")
    public JSONPObject testJSONP(String callback){
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(1000L).setItemDesc("JSONP測試!!!");
        return new JSONPObject(callback, itemDesc);
    }
           

cors跨域方式

實作跨域

實作cors調用

package com.jt.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration  //辨別我是一個配置類
public class CorsConfig implements WebMvcConfigurer {

    //在後端 配置cors允許通路的政策
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET","POST") //定義允許跨域的請求類型
                .allowedOrigins("*")           //任意網址都可以通路
                .allowCredentials(true) //是否允許攜帶cookie
                .maxAge(1800);                 //設定請求長連結逾時時間.
    }
}

           

總結

1.jsonp

jsonp本質利用javaScript中的src屬性的get請求實作的跨域.

傳回值必須經過特殊的格式封裝.

2.cors

添加在響應頭中資訊.指定哪些伺服器允許通路.

繼續閱讀