有一个场景(跨域产生唯一uuid)需要在跨域的情况下读写cookie,中间调试过程遇到了很多问题,最终调通,记录一下:
前端代码:(调试工具: http://www.w3school.com.cn/tiy/t.asp?f=jquery_ajax_get)
<!DOCTYPE html><html><head><script src=”/jquery/jquery-1.11.1.min.js”></script><script>$(document).ready(function(){ $(“button”).click(function(){
$.ajax({ url: “http://192.168.1.233:8061/uc/test2”, type: “GET”, xhrFields: { withCredentials: true }, crossDomain: true, success: function (data) { alert(“数据:” + data.data); } });
});});</script></head><body>
<button>向页面发送 HTTP GET 请求,然后获得返回的结果</button>
</body></html>
后端服务需要进行的设置:
后台需要设置:
origin := c.Request.Header.Get(“Origin”)
c.Header(“Access-Control-Allow-Origin”, origin)
c.Header(“Access-Control-Allow-Credentials”, “true”)
后端测试代码:
g.GET(“/uc/test2”, func(c *gin.Context) {
method := c.Request.Method //请求方法
origin := c.Request.Header.Get(“Origin”) //请求头部
var headerKeys []string // 声明请求头keys
for k := range c.Request.Header {
headerKeys = Append(headerKeys, k)
}
if origin != “” {
c.Header(“Access-Control-Allow-Origin”, origin) // 这是允许访问所有域
c.Header(“Access-Control-Allow-Methods”, “POST, GET, OPTIONS, PUT, DELETE,UPDATE”) //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次’预检’请求
// header的类型
c.Header(“Access-Control-Allow-Headers”, “Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma”)
// 允许跨域设置 可以返回其他子段
c.Header(“Access-Control-Expose-Headers”, “Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma”) // 跨域关键设置 让浏览器可以解析
c.Header(“Access-Control-Max-Age”, “172800”) // 缓存请求信息 单位为秒
c.Header(“Access-Control-Allow-Credentials”, “true”) // 跨域请求是否需要带cookie信息 默认设置为true
c.Set(“content-type”, “application/json”) // 设置返回格式是json
}
//放行所有OPTIONS方法
if method == “OPTIONS” {
c.AbortWithStatus(200)
}
now := time.Now().String()
val, err := c.Cookie(“name”)
if err != nil {
c.SetCookie(“name”, now, 10000, “*”, “*”, false, true)
val = now
}
c.JSON(200, gin.H{
“code”: 0,
“message”: “”,
“data”: val,
})
})