一,配置网关
1.1前端项目配置
- 在前端项目找到static/config/index.js文件, 找到api请求地址改为:localhost.http://localhost:88/api’
- getMenus() {
this.KaTeX parse error: Expected '}', got 'EOF' at end of input: … url: this.http.adornUrl(“/product/category/list/tree”),
method: “get”
}).then(({ data }) => {
console.log(“成功获取到菜单数据…”, data.data);
this.menus = data.data;
});
},
3. 这样就能往api地址发送product/category/list/tree"的get请求.
1.2后端renrne-fast项目配置
此时是直接给nacos发请求,fast发验证码需要也连上nacos.
1. 配置pom文件加入common模块依赖,和gson依赖
2. 在applicaction.yml文件配置nacos的配置
# nacos前端网关转发
mvc:
throw-exception-if-no-handler-found: true
application:
name: renren-fast
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
- 在该模块下的renrenapplication的启动文件开启发现功能: @EnableDiscoveryClient,重启项目.
- 查看nacos,renren-fast项目是否上线
1.3在gateway(以在nacos配置)网关项目配置
1.配置断言
- id: admin_route
# lb:开启负载均衡
uri: lb://renren-fast
# 前端项目只要带/api全部路由到fast项目
predicates:
- Path=/api/**
# filters:路径重写功能
filters:
// 正则表达式:(?<segment>.*)匹配所有:/api的路径,会被重定向到 /renren-fast/xxx 路径上,其中 xxx 是原始请求中的路径片段
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}
二.跨域
p46:登录前端项目报错:88端口登录8081端口项目报错,:by CORS policy!
跨域:浏览器不能执行其他网站的脚本,它是浏览器的同源策略导致的,是浏览器对jaascript施加的安全限制.
跨域方法:非简单请求(put,DELETD)等,需要先发送预检请求.
- 预检请求,OPTIONS
- 想要允许开宇
- 发送真实请求
- 响应数据
解决跨域 一
- 使用nginx部署为同一域,
静态请求:http://nginx/xxx转发给vue-admin
动态请求:http://nginx/api/xxx转发给gateway反向代理到具体模块服务
解决跨域 二
- 给预检请求告诉服务器允许跨域:添加响应头
- 新建gateway/config/GulimallCorsConfiguration.
//具体代码
@Configuration
public class GulimallCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//1、配置跨域
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}