api之未在Vue页面上检测到Cookie
shangdawei
阅读:186
2025-06-02 22:19:02
评论:0
每当用户发出API请求时,我都会检查 session 是否有效
userCookie, err := r.Cookie("session-id")
if err != nil {
fmt.Println(err)
if strings.HasPrefix(r.URL.Path, "/login") {
Login(w, r, db) //login and create session
}
} else {
//Authenticate Session Then if Valid proceed to my APIs
}
因此,当我直接在浏览器的搜索栏上使用API时,它就可以工作,因为它可以检测到 session cookie,但是当我在Vue / axios上使用它时,它却无法检测到cookie,并且会出现以下错误:
http: named cookie not present
exit status 1
创建 session 时,我将cookie设置为
Path: "/",因此即使服务器和前端具有不同的端口, session cookie也会生成到我的Vue页面。
那么,如何使服务器在Vue页面上检测到我的 session cookie?
请您参考如下方法:
您需要设置 withCredentials 以在CORS请求上发送cookie(并且由于您具有不同的端口,因此将其视为不同的服务器)。
axios.interceptors.request.use(
function(config) {
// Do something before request is sent
config.withCredentials = true;
return config;
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
要么
axiox.get('/', { withCredentials: true })
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



