SpringBoot与Vue交互解决跨域问题帮我解决
时间: 2024-03-22 10:40:11 浏览: 17
好的,下面是解决 Spring Boot 与 Vue 跨域问题的一种方法。
首先,在 Spring Boot 的后端代码里,我们需要在 Controller 上添加 `@CrossOrigin` 注解,来允许跨域访问。示例代码如下:
```java
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
```
其中 `@CrossOrigin(origins = "*", maxAge = 3600)` 表示允许所有来源的跨域访问,并设置了缓存时间为 3600 秒。
然后,在 Vue 的前端代码里,我们需要在 Axios 请求中设置 `withCredentials: true`,来开启跨域请求。示例代码如下:
```javascript
axios.get('http://localhost:8080/hello', { withCredentials: true })
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
```
其中 `withCredentials: true` 表示允许发送跨域凭证,例如 Cookie 等。
最后,在 Spring Boot 的后端代码里,我们需要添加一个 Filter,来允许前端发送跨域凭证。示例代码如下:
```java
@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
```
其中 `config.setAllowCredentials(true)` 表示允许发送跨域凭证。
以上就是解决 Spring Boot 与 Vue 跨域问题的一种方法,希望能够帮到您。