问题一、Vue请求无法发送cookie,后端无法获取cookie的问题;
1、今天在实现 Vue + Beego 项目的登录功能时,出现 Vue 发送请求之后,Beego 居然无法获取 cookie 的问题,上代码:
- 前端 api.js 文件添加 withCredentials 设置:
import axios from 'axios'
axios.defaults.withCredentials = true
- 后端 app.conf 文件设置启用 session 和 cookie
sessionon = true
sesionname="pm_manager"
sessiongcmaxlifetime="3600"
sessioncookielifetime="3600"
SessionAutoSetCookie = true
copyrequestbody = true
- 后端 controller 中直接读取 cookie
func (c *LoginController) LoginFunction() {
// 1、直接输出 cookie 的值 ,第一次请求时,cookie 是为空的
fmt.Println(" cookie = ", c.Ctx.GetCookie("uname"))
c.Ctx.SetCookie("uname", "Cookiezhangsan", time.Second*3600)
var results Results
results.Code = "200"
results.Result = 1
results.Message = "登录成功"
c.Data["json"] = results
c.ServeJSON()
}
发送第一次请求,控制台输出:
cookie =
发送第二次请求,控制台输出:
cookie = Cookiezhangsan
- 到了这里,那么 Vue 和 Beego 之间传递 cookie 的问题就算是解决了
问题二、解决Vue的axios设置withCredentials之后跨域问题;
- 但是新问题又出现了,
Vue 添加 axios.defaults.withCredentials = true 配置之后,发送请求出现了跨域问题,去掉配置之后又解决了。
- 解决方法有几种,但是我这里 Beego 用的是 cors 来解决跨域的,所以目前就只有以下解决方法
跨域报错信息:
Access to XMLHttpRequest at 'http://localhost:8080/loginfunction?username=cxz&password=cxz&lesseeid=10010' from origin 'http://localhost:8081' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
大致原因是浏览器要求服务器返回的 response headers 中 Access-Control-Allow-Origin 不能是 * 的,要使用具体的 url ;
这就是出现报错时候的 response headers 了,很明显 Access-Control-Allow-Origin 就是 *
- 解决:
修改 Beego 的 main.go 中 cors 的配置
将 AllowAllOrigins: true, 改为 AllowOrigins: []string{"http://localhost:8081"}, 即可
func init() {
models.MysqlLink()
//InsertFilter是提供一个过滤函数
beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
// 允许访问所有源
// AllowAllOrigins: true,
// 只允许 localhost:9191 访问
AllowOrigins: []string{"http://localhost:8081"},
// 可选参数"GET", "POST", "PUT", "DELETE", "OPTIONS" (*为所有)
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
// 指的是允许的Header的种类
AllowHeaders: []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "Access-Control-Allow-Credentials"},
// 公开的HTTP标头列表
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
// 如果设置,则允许共享身份验证凭据,例如cookie
AllowCredentials: true,
}))
}
cors 修改之后,重启 Beego 项目,使用 Vue 重新发送请求
可以看到 Access-Control-Allow-Origin 的值变成了 ,cors 设置的 http://localhost:8081 ,前端控制台也没有报跨域异常了;
大家有什么问题,欢迎留言评论,一起探讨,解决~~~