手把手教你解决跨域问题
上一章节提到了跨域,在本章节将详细介绍springboot 打包jar包 + Tomcat 运行前端项目的方式资源访问跨域问题。
如果前端项目以及后端项目都部署到同一个服务器上,是不存在跨域问题的,但是往往我们会把服务器部署后端项目以及数据库,前端项目在本地开发过程中会需要访问云端服务器,因此跨域问题是难以避免的!
下面讲讲怎么配置非ngnix的跨域配置,如果是ngnix的方式请自行查找资料。
直接上代码!
springboot项目中重写WebMvcConfigurer:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域配置
*
* @author hxd
* @date 2023/3/1
*/
@Configuration // 必须要加
public class CorsConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigure() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").
allowedOrigins("*"). //允许跨域的域名,可以用*表示允许任何域名使用
allowedMethods("*"). //允许任何方法(post、get等)
allowedHeaders("*"). //允许任何请求头
allowCredentials(true). //带上cookie信息
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
};
}
}
打包部署上去后,local 前端访问云服务器地址试试
完美解决!