跨域访问测试

同域测试

分析

1.浏览器地址:http://manage.jt.com/test.html
2.浏览器地址: http://manage.jt.com/test.json

结论

当浏览器地址与ajax请求的地址(协议://域名:端口)相同时可以实现正常的义务调用.

跨域测试

分析

1.浏览器地址: http://www.jt.com/test.html
2.2.ajax请求地址: http://manage.jt.com/test.json

结论

如果请求地址(协议://域名:端口)不相同则导致请求调用失败

浏览器-同源策略说明

说明:浏览器规定发起ajax请求时如果请求协议/域名/端口号如果三种中有一个与当前浏览器的地址不相同时,则违反了同源策略的规定,则浏览器不予以解析返回值.
跨域问题:违反同源策略的规定就是跨域请求.

跨域-JSONP

JSONP垮域原理

1.利用javascrpit中的src属性实现跨域请求.
2.自定义回调函数 function callback(xxx).
3.将返回值结果进行特殊格式封装 callback(json).
4.由于利用src属性进行调用 所以只支持get请求类型
封装返回值
hello({"id":"1","name":"tom"})
页面js编辑
<!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>

JSONP

JSONP(JSON with Padding)是JSON的一种使用模式,可用于解决主流浏览器的跨域数据访问问题.由于同源策略,一般来说位于 server1.example.com的网页无法与不是 server1.example.com的服务器进行沟通.

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+")";
     }

}

控制台输出

image

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调用原理

image

实现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);                 //设定请求长链接超时时间.
    }
}

cors调用响应头解析

image

cors跨域测试

image

JSON数据格式

image

关于跨域的总结

1.jsonp

jsonp本质利用javaScript中的src属性的get请求实现的跨域
返回值必须经过特殊格式封装

2.cors

添加在响应头中的信息,指定在那些服务器中访问

BolunWu
4 声望3 粉丝

下一篇 »
京淘Day17