谷粒商城 p46前端配置nacos网关转发,跨域

一,配置网关

1.1前端项目配置

  1. 在前端项目找到static/config/index.js文件, 找到api请求地址改为:localhost.http://localhost:88/api’
  2. 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
  1. 在该模块下的renrenapplication的启动文件开启发现功能: @EnableDiscoveryClient,重启项目.
  2. 查看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)等,需要先发送预检请求.

  1. 预检请求,OPTIONS
  2. 想要允许开宇
  3. 发送真实请求
  4. 响应数据

解决跨域 一

  1. 使用nginx部署为同一域,
    静态请求:http://nginx/xxx转发给vue-admin
    动态请求:http://nginx/api/xxx转发给gateway反向代理到具体模块服务

解决跨域 二

  1. 给预检请求告诉服务器允许跨域:添加响应头
  2. 新建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);
    }
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值