目录
🧨🧨🧨
大家好,我是搞全栈的半夏 🧑,一个热爱写文的全栈工程师 💻.
如果喜欢我的文章,可以关注 ➕ 点赞 👍 一起学习交流全栈开发,成为更优秀的工程师🧨🧨🧨
前言
在前面两篇文章中,我们已经完成了前后端项目的搭建。既然是前后端分离的项目,那肯定绕不开使用XMLHttpRequest
发送请求。
在XMLHttpRequest
的基础上,Jquery封装了Ajax方便在WEB 发送请求。后来又出现了Axios,Axios基于XMLHttpRequest
(浏览器)和http
(Node)封装,这使得Axios既可以在浏览器使用,也可以在Node服务端环境下使用。
再到现在出现的不基于XMLHttpRequest
的fetch。
而在真实企业开发中,前端通常使用Axios
来发送请求,本文主要介绍Axios如何发送请求,以及前后端跨域问题的解决。
安装Axios
打开终端,输入yarn add axios
,回车~
测试访问test接口
还记得在创建后端项目的时,我们添加了一个test
接口,那我们就来使用Axios来请求这个接口。
先删除src\App.vue
中template
中所有代码,然后在里面添加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
,这就是出现了跨域问题。
跨域出现场景
同一域名,不同文件或路径 - 不跨域
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 局部跨域
- 应用在
Controller
类上面,可以允许该类下面的所有接口接收跨域请求
在TestController
类上添加@CrossOrigin
@CrossOrigin
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping
public String test(){
return "我是测试接口";
}
}
- 应用在
Controller
类的某个方法上,可以允许该方法接收跨域请求
在TestController
的test
上添加@CrossOrigin
@RestController
@RequestMapping("/test")
public class TestController {
@CrossOrigin
@GetMapping
public String test(){
return "我是测试接口";
}
}
实现WebMvcConfigurer
全局跨域
WebMvcConfigurer
是一个接口,提供很多自定义的拦截器,例如跨域设置、类型转化器等等。可以说此接口为开发者提前想到了很多拦截层面的需求,方便开发者自由选择使用。由于Spring5.0
废弃了WebMvcConfigurerAdapter
,所以WebMvcConfigurer
继承了WebMvcConfigurerAdapter
大部分内容。其中一个方法就是addCorsMappings()
,是专门为开发人员解决跨域而诞生的接口。其中构造参数为CorsRegistry
。
具体做法:
- 使用
@Configuration
声明一个配置类,SpringBoot
会自动扫描 - 实现
WebMvcConfigurer
- 重写
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地址。否则还是会报跨域错误
拦截器 全局跨域
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
,允许设置单一来源