欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot +element-axios跨域请求

程序员文章站 2023-12-02 12:51:46
1、初始化element项目 1.1:vue init webpage '项目名称' 1.2:npm i element-ui -S 1.3:在main.js添加 2、添加axios跨域请求 在main.js中添加 3、创建页面 4、创建springboot项目 4.1添加一个controller类 ......

1、初始化element项目
  1.1:vue init webpage '项目名称'


  1.2:npm i element-ui -s


  1.3:在main.js添加
  

import elementui from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
vue.use(elementui)

 

2、添加axios跨域请求

  在main.js中添加
  

/**
  * 跨域设置
  * @type {axiosstatic}
  */
  import axios from 'axios'
  vue.prototype.$axios = axios
  vue.config.productiontip = false
  axios.defaults.withcredentials = false//这个默认即为false,如果改为true,可以传递session信息,后端要做相应修改来放行,

 

3、创建页面

<template>
  <el-button @click="post">发送请求</el-button>
</template>

<script>
  import axios from "axios";
  export default {

    data() {
      return {
        activeindex2: '1'
      };
    },
    methods: {
      handleselect(key, keypath) {
        console.log(key, keypath);
      },
      post(){
        axios.get('http://localhost:8080/test')
          .then(function (response) {
            console.log(response,"已经成功发送请求!");
          })
          .catch(function (error) {
            console.log("请求失败!");
          });
      }


    }
  }
</script>

 

4、创建springboot项目

  4.1添加一个controller类

@controller
@crossorigin
public class testcontroller {


    @requestmapping("/test")
    @responsebody
    public jsonresponseext test(){
        system.out.println("在执行~~~~~~~~~");
        return jsonresponseext.success("执行");
    }

}
jsonresponseext是我自己封装的一个类,你们可以直接返回一个对象或者字符串也是可以的
另外,在controller类里要添加@crossorigin注解,否则前端返回结果会报错

springboot +element-axios跨域请求

   你也可以自己封装一个配置类例如

@configuration
public class corsconfig  extends webmvcconfigureradapter {

    @override
    public void addcorsmappings(corsregistry registry) {
        system.out.println("----------------------");
        registry.addmapping("/**")
                .allowedorigins("*")
                .allowcredentials(true)
                .allowedmethods("get", "post", "delete", "put")
                .maxage(3600);
    }


}

5、测试结果

springboot +element-axios跨域请求