SpringBoot+Vue+Axios cookie跨域处理

2023-11-27 15:05:29 浏览数 (1)

话不多说直接上代码 vue: mian.js

代码语言:javascript复制
import Vue from 'vue'
import App from './App'
import axios from "axios"
axios.defaults.withCredentials=true //允许cookie跨域
Vue.config.productionTip = false
Vue.prototype.$axios = axios//初始化axios
/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

SpringBoot: config:

代码语言:javascript复制
@Configuration
public class cors {
    @Bean
    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOriginPatterns("*") 
                        .allowCredentials(true); //允许cookie跨域
            }
        };
    }
}

axios发送请求

代码语言:javascript复制
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
    addsession(){
      this.$axios.get("http://localhost:8080/testsession/addsession").then(res=>{
        console.log(res);
      })
    },
    getsession(){
      this.$axios.get("http://localhost:8080/testsession/getsession").then(res=>{
        console.log(res);
      })
    }
  }
}
</script>
代码语言:javascript复制
@RestController
@RequestMapping("/testsession")
public class sessionController {
    @RequestMapping("/addsession")
    public void addsession(HttpServletRequest request){
        System.out.println(1);
        request.getSession().setAttribute("users",1);
    }
    @RequestMapping("/getsession")
    public void getsession(HttpServletRequest request){
        Object users = request.getSession().getAttribute("users");
        System.out.println(users);
    }
}

0 人点赞