本篇文章给大家带来的内容是关于springboot和element-axios如何实现跨域请求(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

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如何实现跨域请求(代码)-LMLPHP

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

@Configurationpublic 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如何实现跨域请求(代码)-LMLPHP

相关推荐:

axios请求如何跨域

vue-cli axios请求与跨域

以上就是springboot和element-axios如何实现跨域请求(代码)的详细内容,更多请关注Work网其它相关文章!

09-14 06:32