在开发前后端分离项目时,`Spring Boot`搭配`Vue`和`Apache Shiro`是一种常见组合。然而,当涉及到跨域请求时,很多小伙伴可能会遇到`CORS`(跨域资源共享)问题。比如:`No 'Access-Control-Allow-Origin' header is present on the requested resource.`。
首先,我们需要在`Spring Boot`后端配置跨域支持。可以通过创建一个全局的`@Configuration`类来实现:
```java
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("") // 允许所有域名访问
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("");
}
};
}
}
```
同时,在`Vue`前端也要确保正确设置请求头。例如使用`axios`时,可以这样配置:
```javascript
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
```
通过以上步骤,你的跨域问题基本就能得到解决了!🚀
技术分享 SpringBoot Vue Shiro 跨域问题