api - 未在Vue页面上检测到Cookie

标签 api vue.js go cookies

每当用户发出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 })

关于api - 未在Vue页面上检测到Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606662/

相关文章:

api - 为什么 Files.exists(…) 和 Files.notExists(…)?

javascript - Vuex 状态项始终为空

javascript - vuejs 复制数据对象并删除属性也会从原始对象中删除该属性

go - 全局变量地址

java - 下游服务健康检查

javascript - 未捕获的语法错误 : Unexpected identifier on AJAX call back function

javascript - Vuejs - 冒泡自定义事件

go - GO中获取数据报的目的地址

转到接口(interface) : Cannot assign value to unexported field

javascript - 使用 Solr 或 ElasticSearch 作为 API 最佳实践