个人博客-SpringBoot+Vue3项目实战(4)前后端联调并解决跨域问题

🧨🧨🧨

大家好,我是搞全栈的半夏 🧑,一个热爱写文的全栈工程师 💻.
如果喜欢我的文章,可以关注 ➕ 点赞 👍 一起学习交流全栈开发,成为更优秀的工程师

🧨🧨🧨

前言

在前面两篇文章中,我们已经完成了前后端项目的搭建。既然是前后端分离的项目,那肯定绕不开使用XMLHttpRequest发送请求。

XMLHttpRequest的基础上,Jquery封装了Ajax方便在WEB 发送请求。后来又出现了Axios,Axios基于XMLHttpRequest(浏览器)和http (Node)封装,这使得Axios既可以在浏览器使用,也可以在Node服务端环境下使用。

再到现在出现的不基于XMLHttpRequestfetch

而在真实企业开发中,前端通常使用Axios来发送请求,本文主要介绍Axios如何发送请求,以及前后端跨域问题的解决。

image-20230118160918332

安装Axios

打开终端,输入yarn add axios,回车~

image-20230118161306354

测试访问test接口

还记得在创建后端项目的时,我们添加了一个test接口,那我们就来使用Axios来请求这个接口。

先删除src\App.vuetemplate中所有代码,然后在里面添加button

  <button @click="reqTest"> 请求tes接口</button>

然后在script中引入Axios

import axios from "axios";

实现reqTest方法。test接口是一个get接口,同时不需要任何参数。

const reqTest = () => {
  axios.get("http://localhost:8080/test")
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
}

浏览器打开网页,F12,打开开发者工具,查看Network。点击按钮,发送请求。发现访问出错。提示CORS error,这就是出现了跨域问题。

image-20230118165521029

跨域出现场景

同一域名,不同文件或路径 - 不跨域


http://www.domain.com/a.js
http://www.domain.com/b.js         
http://www.domain.com/folder/c.js

同一域名,不同端口 - 跨域

http://www.domain.com:8000/a.js
http://www.domain.com/b.js

同一域名,不同协议 - 跨域

http://www.domain.com/a.js
https://www.domain.com/b.js 

域名和域名对应相同ip - 跨域

www.domain.com对应的ip是192.168.1.1,通过域名和ip两种方式会出现跨域。

http://www.domain.com/a.js
http://192.168.1.1/b.js 

主域相同,子域不同 - 跨域

http://www.domain.com/a.js
http://x.domain.com/b.js           
http://domain.com/c.js

不同域名 - 跨域

http://www.domain1.com/a.js
http://www.domain2.com/b.js 

SpringBoot 解决跨域

@CrossOrigin 局部跨域

  1. 应用在 Controller 类上面,可以允许该类下面的所有接口接收跨域请求

TestController类上添加@CrossOrigin

@CrossOrigin
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping
    public String test(){
        return "我是测试接口";
    }
}
  1. 应用在 Controller 类的某个方法上,可以允许该方法接收跨域请求

TestControllertest上添加@CrossOrigin

@RestController
@RequestMapping("/test")
public class TestController {
    @CrossOrigin
    @GetMapping
    public String test(){
        return "我是测试接口";
    }
}

实现WebMvcConfigurer全局跨域

WebMvcConfigurer是一个接口,提供很多自定义的拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0废弃了WebMvcConfigurerAdapter,所以WebMvcConfigurer继承了WebMvcConfigurerAdapter大部分内容。其中一个方法就是addCorsMappings(),是专门为开发人员解决跨域而诞生的接口。其中构造参数为CorsRegistry

具体做法:

  1. 使用 @Configuration声明一个配置类,SpringBoot会自动扫描
  2. 实现WebMvcConfigurer
  3. 重写addCorsMappings方法
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("http://127.0.0.1:5173") // 这里设置请求的来源。vite启动项目默认是5173端口
		.allowedHeaders("*")
        .allowedMethods("GET", "POST", "PUT", "DELETE")
		.allowCredentials(true)
		.maxAge(86400);
    }
}

注意

1. allowedOrigins(“http://127.0.0.1:5173”) // 这里设置请求的来源(白名单)。vite启动项目默认是5173端口。allowedOrigins(“*”)表示接收所有来源的请求

2. 如果后台指定路径来源为:http://127.0.0.1:5173那么在浏览器里访问前端页面的时候,必须用 http://127.0.0.1:5173,不可以写成http://localhost:5173或者本机ip地址。否则还是会报跨域错误

image-20230128090014761

拦截器 全局跨域

Spring MVC 4.2内置了一个CorsFilter专门用于处理CORS请求问题,它所在的路径是:org.springframework.web.filter.CorsFilter。通过配置这个Filter使它生效便可统一控制跨域请求:

@Configuration
public class FilterCorsConfig {
    /**
     * 允许跨域调用的过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许白名单域名进行跨域调用
        config.addAllowedOriginPattern("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

注意

如果有小伙伴,在网上copy的是config.addAllowedOrigin("*");,出现下面的问题

When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the “Access-Control-Allow-Origin” response header. To allow credentials to a set of origins, list them explicitly or consider using “allowedOriginPatterns” instead.

当allowCredentials为true时,allowingOrigins不能包含特殊值“ *”,因为无法在“ Access-Control-Allow-Origin”响应标头上设置。要允许凭据具有一组来源,请明确列出它们或考虑改用“ allowedOriginPatterns”。

解决方法::将allowingOrigins换成allowedOriginPatterns/allowedOriginPattern即可。

allowedOriginPatterns传入List,允许设置多个来源,

allowedOriginPattern传入String,允许设置单一来源

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YOLO大王

你的打赏,我的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值