跨域问题在前后端分离项目很常见,至于为什么会跨域,同源策略,百度各种博客都很详细,这里不再介绍,主要记录项目中的各种设置,解决的过程。 首先是后端: 过滤器:
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
config.setAllowCredentials(true);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
如果setAllowCredentials 为true,则config.addAllowedOrigin("*") 的参数就不能是*,必须指明,这里直接注释掉,使用addAllowedOriginPattern
Controller层:  路径里包含了web,这个很重要,记住
yml文件:  后端的端口8086,应用上下文路径:/weijianweiAdminApi
再是前端: dev.env.js中设置BASE_API为/web  在index.js中设置dev里面的proxyTable,这里是在开发过程中,在node.js上实现的一个转发,将请求转发到后端,主要解决了开发过程中的跨域问题。  设置完这些以后,npm run dev,项目在本地可以运行了 
开发完成以后,项目打包,放到服务器上: 首先在服务器的nginx的html文件夹中创建文件夹命名为weijianwei 将npm run build 打包生成的文件放在weijianwei中:  修改index里面的assetsPublicPath为weijianwei,对应上面文件夹名称 
设置nginx配置文件nginx.conf:
server {
listen 8099;
server_name localhost;
location /weijianweiAdminApi/ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
client_max_body_size 200m;
proxy_pass http://localhost:8086;
}
}
监听端口8099,匹配路径weijianweiAdminApi,将其转发到http://localhost:8086上, 此时访问项目:http://localhost:8099/weijianwei 成功出现页面,登录时候,预检请求通过,正式请求报跨域问题 前端项目prod.env.js设置 BASE_API:  成功登录访问
|