解决vue请求gin框架接口cros跨域cookie和session失效的问题

  1. 问题

有时候在使用vue请求api接口的时候多个地址没法共享 session,也就是 session会丢失,这是什么原因导致的呢? 由于 session是基于cookie的,ajax请求没法共享session主要是因为 cookie跨域引起的,那么cookie跨域如何解决呢?
  1. gin后端

gin后端配置 跨域访问
func main() {
    //初始化路由,会设置默认中间件:engine.Use(Logger(), Recovery()),可以使用gin.New()来设置路由
    r := gin.Default()
    //配置gin允许跨域请求
    r.Use(cors.New(cors.Config{  //自定义配置
        AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},  //允许的方法
        AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization"},  //header允许山高月小
        AllowCredentials: false,
        MaxAge:           12 * time.Hour,  //有效时间
        ExposeHeaders:    []string{"Content-Length"},
        AllowOriginFunc: func(origin string) bool {  //允许的域
            return true  //所有
        },
    }))
}
参数说明:
AllowAllOrigins 允许全部来源设置为true则所有域名都可以访问本网站接口,可以将此配置换成为AllowOrigins:[“允许访问的域名”]
AllowOrigins:[“允许访问的域名”]
AllowMethods :允许的请求类型
AllowHeaders:允许的头部信息
ExposeHeaders:允许暴露的头信息
AllowCredentials:如果设置,允许共享AuthTuffic证书,如Cookie
  1. 前端 vue ajax请求解决cookie跨域 vue-resource

this.$http.get('getlogin',{ credentials: true }).then(res => {
    console.log(res)
})

this.$http.post('postlogin',{userInfo: $('.form-signin').serialize()},{ credentials: true }).then(res => {
    if(res.body.status != 200) {
        console.log('登录失败')
    }else {
        console.log('登录成功')
    }
})
  1. jquery中ajax请求api cookie跨域

$.ajax({
    url: "http://localhost:8080/comment",
    type: "GET",
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    success: function (data) {
        render(data);
    }
 });
  1. axios ajax请求api cookie跨域

const service = axios.create({
  baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
  timeout: 5000, // 请求的超时时间
  //设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
  // headers: {  
    // "Content-Type": "application/x-www-form-urlencoded"
  // },
  withCredentials: true // 允许携带cookie
})
  1. 原生js中ajax请求api cookie跨域

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/api');
xhr.withCredentials = true;
xhr.onload = onLoadHandler;
xhr.send()

你可能感兴趣的:(前端,#,vue,#,gin框架开发,vue.js,gin,javascript)