前后端分离解决跨域问题:springboot做后端+vue做前端

本文详细介绍了一种在Vue前端与SpringBoot后端间实现跨域请求的方法。通过使用axios库进行前后端数据交互,展示了如何在main.js中配置axios,以及在Login.vue组件中设置后端接口地址。同时,介绍了后端通过@Controller注解实现跨域访问的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单描述一下项目情况:

我们目前暂时是在本地电脑上不同localhost端口直接实现跨域,请求数据。这么简简单单的问题。我花了好多时间去查资料。结果没想到很简单就实现了。

前端部分:

使用axios获取后端数据:

1.安装axios:

npm install axios

 

 


2.main.js中导入
  import axios from 'axios'; /* 引入axios进行地址访问*/
  Vue.prototype.$http = axios;
  (注意:不使用use来使用该例,而是用prototype原型来使用)

 

3.login.vue中:设置后端的接口地址

 Login.vue

<template>
  <div>
    <div>
      <label>邮箱:<input type="text" v-model="email" placeholder="请输入你的邮箱"></label>
    </div>
    <div>
      <label>密码:<input type="password" v-model="password" placeholder="请输入你的密码"></label>
    </div>
    <div>
      <p>{{tip}}</p>
      <a href="#" id="forget">忘记密码?</a>
    </div>
    <div>
      <button @click="login">登录</button>
      <button @click="register">注册</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "login",
  data() {
    return {
      email: "",
      password: "",
      tip: ""
    }
  },
  methods: {
    login: function () {
      let data = new FormData();
      data.append('email',this.email);
      data.append('password',this.password);
      this.$axios.post("http://localhost:9527/user/login", data).then(function (response) {
        console.log(response.data);
      }).catch(function (error) {
        console.log(error);
      })
    },

    register: function () {
      let data = new FormData();
      data.append('email',this.email);
      data.append('password',this.password);
      this.$axios.post("http://localhost:9527/user/register", data).then(function (response) {
        console.log(response.data);
      }).catch(function (error) {
        console.log(error);
      })
    }
  }

}
</script>

<style scoped>

</style>

4.在index.js里面添加路由

import Login from '@/components/Login'
routes:{
      path: '/login',
      name: Login,
      component: Login
    }

 

后端部分:

在控制器类里面设置,前端的地址:

 @CrossOrigin(origins = "http://localhost:8080", maxAge = 3600)

 

 

 

就完成了。

不可思议。

也许还有很多其他办法。等以后遇到了再总结。

 

 

 

 

参考别人:

https://www.cnblogs.com/xintao/p/10751806.html

Vue安装Axios及使用
1.安装:npm install axios --save-dev


2.main.js中导入
  import axios from 'axios'; /* 引入axios进行地址访问*/
  Vue.prototype.$http = axios;
  (注意:不使用use来使用该例,而是用prototype原型来使用)

3.login.vue中:
  import axios from 'axios';

  axios.post("/api/login?", params).then(function(res) {
    var data = res.data;
    // console.log(data);
    let role = data.result.user.role;
    let token = data.result.token;
    localStorage.setItem("currentUser_token", token); //将token存到本地的localStorage中
    // console.log(localStorage);
    if (data.code == 1) {
    alert(data.msg);
    let _username;
    // console.log(localStorage.getItem("currentUser_token"))
    // console.log(userName)
    that.$router.push({path: "/index",query: { name: userName, role: role }});	//跳转到 index页面中并传递name和role的值

    (在index页面中接受参数:PS:let userName = this.$route.query.name;let userRole = this.$route.query.role;)

  } else {

    alert(data.msg);
  }
  }).catch(function(err) {
    console.log("LOGIN_" + err);
  });
(注意:若要使用全局路径访问请求则需要在config中的index.js中配置proxyTable)
举例:proxyTable: {
    '/api': {
      target: 'IP+端口', //后端接口地址
      changeOrigin: true, //是否允许跨越
      pathRewrite: {
      '^/api': '/api', //重写,
      }
     }
   },

https://www.jb51.net/article/146888.htm

跨域资源共享CORS(Cross-origin Resource Sharing),是W3C的一个标准,允许浏览器向跨源的服务器发起XMLHttpRequest请求,克服ajax请求只能同源使用的限制。关于CORS的详细解读,可参考阮一峰大神的博客:跨域资源共享CORS详解。本文为通过一个小demo对该博客中分析内容的一些验证。

1.springboot+vue项目的构建和启动

细节不在此赘述,任何简单的springboot项目就可以,而前端vue项目只需用axios发ajax请求即可。

我的demo里填写用户名和密码,然后点击登录按钮向后台发起登录请求,js代码如下:

?

1

2

3

4

5

6

7

8

9

methods:{

     login:function() {

      //var userParams = this.$qs.stringify(this.User);

       /* var userParams = JSON.stringify(this.User);*/

       this.$axios.post("http://localhost:8080/login",this.User).then(res=>{

       alert(res.data);

      });

     }

   }

后台控制器部分,对登录请求的处理:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

/*CORS设置方法1:@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)*/

  @RequestMapping(value="/login",method = RequestMethod.POST, produces = "application/json;charset=UTF-8" )

  @ResponseBody

  public String userlogin(@RequestBody JSONObject user) {

        /*String name=request.getParameter("name");

        String password=request.getParameter("password");*/

        System.out.println("name: " + user.get("name"));

        System.out.println("password: " + user.get("password"));

        String name = (String) user.get("name");

        String password = (String) user.get("password");

    if(name.equals("zsz") && password.equals("888888")){       

            return "login success!";

        }else{

            return "login failed";

        }

  }

后台以8080端口启动,前台以8081启动,此时无法跨域,浏览器控制台会报错:

 

2.springboot设置CORS

此处主要有两种方法(但是貌似有其他博客还有更多种),在springboot中实现都比较简单(反正springboot好像就是各种省事各种简单)。

方法1:

?

1

@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600)

直接在控制器方法前注解,设置可以跨域的源ip和端口,以及预检有效期maxAge等参数。

方法2:

编写配置类,配置全局的CORS设置。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@Configuration

public class MyCorsConfig {

    @Bean

    public WebMvcConfigurer corsConfigurer(){

     return new WebMvcConfigurerAdapter() {

      @Override

      public void addCorsMappings(CorsRegistry registry) {

        // 限制了路径和域名的访问

        /*registry.addMapping("/api*").allowedOrigins("http://localhost:8081");*/

       registry.addMapping("/**")

        .allowedOrigins(ALL)

        .allowedMethods(ALL)

        .allowedHeaders(ALL)

        .allowCredentials(true);

      }

    };

    }      

}

如果路径配置成以上的 /**则对所有源路径均接受跨域访问,当然也可以配置更详细的路径。

这样可以成功访问后台,浏览器中可以看到http请求和响应的结果如下图:

 

3.CORS非简单请求预检请求的抓包验证

根据阮一峰大神的博客所述,CORS简单请求只发送一次请求,服务器设置支持CORS则会在响应内容中添加Acess-Control-Allow-Origin等字段,否则不添加,浏览器知道出错,从而抛出异常;CORS非简单请求时,会先进行一次预检(preflight)请求,浏览器根据响应内容进行正式的XMLHttpRequest请求。

在我的demo中,我通过将http请求的 content-type 设置为application/json进行非简单请求。此处要说明一下,axios默认情况下发送请求的格式是application/json而不是我之前用jQuery发送ajax请求的application/x-www-form-urlencoded, 而我之前用的另一种方法构造查询字符串,最终发送请求的content-type会变为application/x-www-form-urlencoded。

?

1

var userParams = this.$qs.stringify(this.User)

前台请求代码如本文第一节中所示,在axios请求中直接传入User对象即可。在后端不设置CORS的时候,控制器信息为:

 

协议内容为:

 

而设置了CORS,预检请求结果为:

 

请求成功,并且在响应头中添加了各种字段。

再次发起XHR请求后,结果为:

 

以上实验验证证明了两种CORS请求的过程正如预期。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南北极之间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值