首页 > 解决方案 > axios请求标头中未设置cookie

问题描述

  1. 我有 sprin boot 应用程序作为我的后端和前端的 vue js
  2. 两者都在我的本地主机中运行,但端口不同
  3. 我正在使用 axios 对我的后端服务器进行 api 调用
  4. 我的登录 api 工作完美,并使用设置的 cookie 标头返回响应

但是没有在请求标头中设置 cookie 值,并且所有其他 api 都因身份验证问题而失败,因为 cookie 值(会话 id)不存在于标头
示例响应标头中,并在身份验证时设置了 cookie

HTTP/1.1 200 OK
X-Powered-By: Express
set-cookie: JSESSIONID=C6A3DE7E13C60F33D777875DB610EED2; Path=/a; HttpOnly
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: 0
x-frame-options: DENY
content-type: application/json;charset=UTF-8
transfer-encoding: chunked
date: Tue, 12 May 2020 15:20:17 GMT
connection: close

下面是我在 vue.config.js 中的代理配置

 devServer: {
    proxy: {
      "/": {
        target: "http://localhost:8080/abc",
        secure: false,
        onProxyReq: function(request) {
          request.setHeader("origin", "http://localhost:8080/abc");
        }
      }
    },
    disableHostCheck: true
  }

这是我使用“withCredentials:true”创建的 axios 实例

  withCredentials: true,
  baseURL: "/",
  headers: { "Content-Type": "application/json" }
});

下面是我在服务器端的网络安全配置


        httpSecurity
                .csrf().disable()
                .httpBasic().disable()
                .authorizeRequests()
                .antMatchers("/auth/login").permitAll()
                .antMatchers("/auth/reset-password").authenticated()
                .anyRequest().authenticated();
    }

注意:这在邮递员中有效,因为邮递员会自动在请求标头中添加 cookie

标签: spring-bootvue.jsaxioscross-domainsetcookie

解决方案


这看起来像是 axios 的一个已知问题。尝试像这样设置默认值

axios.defaults.withCredentials = true

https://github.com/axios/axios/issues/587#issuecomment-275890961


推荐阅读